fastDFS 文件服务器访问

鉴权 token 获取

token 由文件服务器管理员分配

接口定义

上传文件

请求 URL:

http://ip:port/fastdfs/upload/file/sample

请求方式:
  • GET/POST
参数形式:
  • form-data
参数:
参数名位置类型说明是否必填
access_tokenheaderString用户 token
fileurlMultipartFile文件
返回:
参数名必选类型说明
msgString提示
codeInteger错误代码
dataString数据

data 域内容

参数名必选类型说明
filePathString文件的存储位置
fileNameInteger文件的原始名称
fileTypeString文件类型
httpUrlString文件的访问地址(未开启防盗链时可用)
返回示例
{
  "msg": "操作成功",
  "code": 200,
  "data": {
    "filePath": "group1/M00/00/0D/wKjcAl-SNgmAVJK7AACEAGBrbtI245.jpg",
    "fileName": "timg.jpg",
    "fileType": "jpg",
    "httpUrl": "http://192.168.220.2:80/group1/M00/00/0D/wKjcAl-SNgmAVJK7AACEAGBrbtI245.jpg"
  }
}
备注

获取防盗链地址

请求 URL:

http://ip:port/fastdfs/download/fileWithToken

请求方式:
  • GET/POST
参数形式:
  • form-data
参数:
参数名位置类型说明是否必填
access_tokenheaderString用户 token
filePathurlString文件路径
返回:
参数名必选类型说明
msgString提示
codeInteger错误代码
dataString文件的防盗链访问路径
返回示例
{
  "msg": "操作成功",
  "code": 200,
  "data": "http://192.168.220.2:80/group1/M00/00/0D/wKjcAl-SNgmAVJK7AACEAGBrbtI245.jpg?token=639e5738e7c457eb2f061fc0d71a3165&ts=1603417665"
}
备注

删除文件

请求 URL:

http://ip:port/fastdfs/delete/fileDelete

请求方式:
  • GET/POST
参数形式:
  • form-data
参数:
参数名位置类型说明是否必填
access_tokenheaderString用户 token
filePathurlString文件路径
返回:
参数名必选类型说明
msgString提示
codeInteger错误代码
dataInteger0 为正常响应,非 0 为异常响应,文件不存在等
返回示例
{
  "msg": "操作成功",
  "code": 200,
  "data": 0
}
备注

java 调用工具类


import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

public class HttpClientUtil {
	private static Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);
	/**
	 * 路径分隔符
	 */
	public static final String SEPARATOR = "/";
	/**
	 * Point
	 */
	public static final String POINT = ".";
	/**
	 * ContentType
	 */
	public static final Map<String, String> EXT_MAPS = new HashMap<>();
	static {
		initExt();
	}
	public static void initExt() {
		// image
		EXT_MAPS.put("png", "image/png");
		EXT_MAPS.put("gif", "image/gif");
		EXT_MAPS.put("bmp", "image/bmp");
		EXT_MAPS.put("ico", "image/x-ico");
		EXT_MAPS.put("jpeg", "image/jpeg");
		EXT_MAPS.put("jpg", "image/jpeg");
		// 压缩文件
		EXT_MAPS.put("zip", "application/zip");
		EXT_MAPS.put("rar", "application/x-rar");
		// doc
		EXT_MAPS.put("pdf", "application/pdf");
		EXT_MAPS.put("ppt", "application/vnd.ms-powerpoint");
		EXT_MAPS.put("xls", "application/vnd.ms-excel");
		EXT_MAPS.put("xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
		EXT_MAPS.put("pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation");
		EXT_MAPS.put("doc", "application/msword");
		EXT_MAPS.put("doc", "application/wps-office.doc");
		EXT_MAPS.put("docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
		EXT_MAPS.put("txt", "text/plain");
		// 音频
		EXT_MAPS.put("mp4", "video/mp4");
		EXT_MAPS.put("flv", "video/x-flv");
	}



	/**
	 * @Title: postRestData
	 * @TitleExplain: post请求接口
	 * @Description: post请求接口
	 * @param urlStr 请求url
	 * @return String   post响应
	 */
	public static String postDataLikeFormData(String urlStr,MultipartFile file,String fastdfsAccessToken) {
		String result = "";
		// 换行符
		final String newLine = "\r\n";
		final String boundaryPrefix = "--";
		// 定义数据分隔线
		String BOUNDARY = "========7d4a6d158c9";
		// 服务器的域名
		URL url =null;
		HttpURLConnection conn=null;
		DataInputStream in=null;
		try {
			url = new URL(urlStr);
			conn = (HttpURLConnection) url.openConnection();
			// 设置为POST情
			conn.setRequestMethod("POST");
			// 发送POST请求必须设置如下两行
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setUseCaches(false);
			// 设置请求头参数
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("Charsert", "UTF-8");
			conn.setRequestProperty("access_token",fastdfsAccessToken);
			conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);

			OutputStream out = new DataOutputStream(conn.getOutputStream());
			/**
			 * 循环输出
			 *
			 * */
			StringBuilder sb = new StringBuilder();
			sb.append(boundaryPrefix);
			sb.append(BOUNDARY);
			sb.append(newLine);
			sb.append("Content-Disposition: form-data;name=\"file\";filename=\"" + file.getOriginalFilename()
			+ "\"" + newLine);
			String contentType=getContentTypeByFileName(file.getOriginalFilename());
			sb.append("Content-Type:"+contentType);
			sb.append(newLine);
			sb.append(newLine);
			out.write(sb.toString().getBytes());
			byte[] bufferOut = new byte[1024];
			int bytes = 0;
			//如果文件为空则不上传
			if (file.isEmpty() || file.getSize() <= 0) {
				logger.debug("文件为空或大小为0没有上传fastdfs:" + file.getOriginalFilename());
				return null;
			}
			in  = new DataInputStream(file.getInputStream());
			while ((bytes = in.read(bufferOut)) != -1) {
				//bufferOut转化为String之后会损失部分数据,所以之后的操作直接输出,不转化为string
//                        sb.append(new String(bufferOut));
				out.write(bufferOut, 0, bytes);
			}
			sb.append(newLine + boundaryPrefix + BOUNDARY);
			sb.append(boundaryPrefix + newLine);
			byte[] end_data = (newLine + boundaryPrefix + BOUNDARY + boundaryPrefix + newLine).getBytes();
			out.write(end_data);
			logger.debug("请求数据为: "+sb.toString());
			out.flush();
			out.close();
			StringBuffer sbResult = new StringBuffer();
			// 定义BufferedReader输入流来读取URL的响应
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					conn.getInputStream()));
			String line = null;
			while ((line = reader.readLine()) != null) {
//				System.out.println(line);
				sbResult.append(line+"\r\n");
			}
			reader.close();
			result = sbResult.toString();
		} catch (Exception e) {
			logger.error("发送POST请求出现异常!" + e);
		}finally {
			if (conn != null) {
				conn.disconnect();
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		logger.debug("post "+urlStr +",result="+result);
		return result;
	}


	/**
	 * 根据文件名获取contentType
	 * */
	public static String getContentTypeByFileName(String fileName){
		return EXT_MAPS.get(getFilenameSuffix(fileName));
	}
	/**
	 * 获取文件名称的后缀
	 *
	 * @param filename 文件名 或 文件路径
	 * @return 文件后缀
	 */
	public static String getFilenameSuffix(String filename) {
		String suffix = null;
		String originalFilename = filename;
		if (StringUtils.isNotBlank(filename)) {
			if (filename.contains(SEPARATOR)) {
				filename = filename.substring(filename.lastIndexOf(SEPARATOR) + 1);
			}
			if (filename.contains(POINT)) {
				suffix = filename.substring(filename.lastIndexOf(POINT) + 1);
			} else {
				if (logger.isErrorEnabled()) {
					logger.error("filename error without suffix : {}", originalFilename);
				}
			}
		}
		return suffix;
	}

	/**
	 * 从指定系统获取写卡数据
	 *
	 * */
	public static String downloadFile(String urlStr,String filePath,String fastdfsAccessToken){
		String result = null;
		try{
			HttpClient client = new DefaultHttpClient();
			StringBuffer sb=new StringBuffer(urlStr);
			StringBuffer params=new StringBuffer("");
			params.append("filePath=");
			params.append(filePath);
			HttpPost post = new HttpPost(sb.toString());
			//设置header参数
			post.addHeader("access_token",fastdfsAccessToken);
			//设置其它参数
			StringEntity stringEntity = new StringEntity(params.toString());//param参数,可以为"key1=value1&key2=value2"的一串字符串
			stringEntity.setContentType("application/x-www-form-urlencoded");
			post.setEntity(stringEntity);
			HttpResponse resp = client.execute(post);

			BufferedReader brBufferedReader = new BufferedReader(
					new InputStreamReader(resp.getEntity().getContent(), "utf-8"));

			StringBuffer resultSb = new StringBuffer();
			String line = "";
			while ((line = brBufferedReader.readLine()) != null) {
				resultSb.append(line);
			}
			brBufferedReader.close();
			result = resultSb.toString();
		}catch(Exception e){
			logger.error("系统异常:",e);
		}
		return result;
	}

}