記錄一下OpenFeign文件上傳下載接口
上傳
服務提供方接口
@PostMapping("upload")
public void upload(String fileOssName, @RequestBody byte[] bytes) {
OSS ossClient = new OSSClientBuilder().build(END_POINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
ossClient.putObject(BUCKET_NAME_PC, fileOssName, new ByteArrayInputStream(bytes));
ossClient.shutdown();
}
服務接口直接接收byte數組,bytes參數要用@RequsetBody接收
這里最終上傳到阿里雲OSS,換成其他目的地流都類似。
byte數組可以轉化為InputStream: new ByteArrayInputStream(bytes)
服務調用方的遠程接口
@FeignClient("oss-service")
public interface OssFeignService {
@PostMapping("oss/upload")
public Result upload(@RequestParam String fileOssName, @RequestBody byte[] bytes);
}
服務調用方接口
ossFeignService.upload(fileOssName, bytes);
bytes來源為文件或內存,具體看自己業務
下載
服務提供方接口
@GetMapping("download")
public byte[] download(String fileOssName) throws Exception {
OSS ossClient = new OSSClientBuilder().build(END_POINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
OSSObject ossObject = ossClient.getObject(BUCKET_NAME_APP, fileOssName);
InputStream in = ossObject.getObjectContent();
ByteArrayOutputStream out = new ByteArrayOutputStream();
IoUtils.copy(in, out);
out.close();
in.close();
ossClient.shutdown();
return out.toByteArray();
}
這里的InputStream來源於阿里雲OSS,換成其他輸入流都類似
IoUtils是OSS提供的工具類,copy方法其實就是我們平時寫的二進制流的讀寫,源碼如下
static public long copy(InputStream input, OutputStream output) throws IOException {
byte[] buffer = new byte[1024];
int bytesRead;
int totalBytes = 0;
while ((bytesRead = input.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
totalBytes += bytesRead;
}
return totalBytes;
}
服務調用方的遠程接口
@FeignClient("oss-service")
public interface OssFeignService {
@GetMapping("oss/download")
public byte[] download(@RequestParam String fileOssName);
}
服務調用方接口
@GetMapping("download")
public void download(String fileOssName, String fileName, HttpServletRequest request, HttpServletResponse response) throws Exception {
ExcelUtil.setResponseHeader(request, response, fileName);
byte[] bytes = thirdPartyFeignService.downloadFromPc(fileOssName);
OutputStream out = response.getOutputStream();
out.write(bytes);
out.flush();
out.close();
}
其中setResponseHeader方法設置下載頭信息
public static void setResponseHeader(HttpServletRequest request, HttpServletResponse response, String fileName) throws UnsupportedEncodingException {
String agent = request.getHeader("USER-AGENT");
if (null != agent && -1 != agent.indexOf("MSIE") || null != agent && -1 != agent.indexOf("Trident") || null != agent && -1 != agent.indexOf("Edge")) {// ie
fileName = java.net.URLEncoder.encode(fileName, "UTF8");
} else if (null != agent && -1 != agent.indexOf("Mozilla")) {// 火狐,chrome等
fileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
}
response.setContentType("application/octet-stream; charset=utf-8");
response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
response.addHeader("Pargam", "no-cache");
response.addHeader("Cache-Control", "no-cache");
}