鑒權 token 獲取
token 由文件服務器管理員分配
接口定義
上傳文件
請求 URL:
請求方式:
GET/POST
參數形式:
form-data
參數:
參數名位置類型說明是否必填
access_tokenheaderString用戶 token是
fileurlMultipartFile文件是
返回:
參數名必選類型說明
msg是String提示
code是Integer錯誤代碼
data是String數據
data 域內容
參數名必選類型說明
filePath是String文件的存儲位置
fileName是Integer文件的原始名稱
fileType是String文件類型
httpUrl是String文件的訪問地址(未開啟防盜鏈時可用)
返回示例
{
"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:
請求方式:
GET/POST
參數形式:
form-data
參數:
參數名位置類型說明是否必填
access_tokenheaderString用戶 token是
filePathurlString文件路徑是
返回:
參數名必選類型說明
msg是String提示
code是Integer錯誤代碼
data是String文件的防盜鏈訪問路徑
返回示例
{
"msg": "操作成功",
"code": 200,
"data": "http://192.168.220.2:80/group1/M00/00/0D/wKjcAl-SNgmAVJK7AACEAGBrbtI245.jpg?token=639e5738e7c457eb2f061fc0d71a3165&ts=1603417665"
}
備注
刪除文件
請求 URL:
請求方式:
GET/POST
參數形式:
form-data
參數:
參數名位置類型說明是否必填
access_tokenheaderString用戶 token是
filePathurlString文件路徑是
返回:
參數名必選類型說明
msg是String提示
code是Integer錯誤代碼
data是Integer0 為正常響應,非 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 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;
}
}