1、业务需求
外部服务器请求系统文件接口,系统接口返回文件流,并下载到本地。
2、代码实现
外部接口返回map
@GetMapping("/downloadFile")
@ResponseBody
public Map<String,byte[]> downloadFile(String fileUrl){
Map<String,byte[]> map = new HashMap<>();
byte[] bytes = dowLoadFile(fileUrl);
map.put("data",bytes);
return map;
}
public byte[] dowLoadFile(String fileUrl) throws IOException{
FileInputStream in = new FileInputStream(new File(fileUrl));
ByteArrayOutputStream ous = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
while(-1 != (len = in.read(buffer))){
ous.write(buffer,0,len)
}
return ous.toByteArray();
}
使用HttpUtil调用外部接口,实现文件下载到本地
public void downloadFile(String fileUrl) throws IOException{
String host = "http://127.0.0.1:8080";
String url = "/downloadFile?fileUrl=" + fileUrl;
String data = HttpUtil.createGet(host + url).execute().body();
JSONObject json = JSONUtil.parseObj(data);
Object obj = json.get("data");
byte[] bytes = Convert.toPrimitveByteArray(obj);
String suffix = fileUrl.substring(fileUrl.lastIndexOf("."));
String fileName = "新的文件名" + suffix;
FileOutputStream out = new FileOutputStream("D:/yyk/tt/" + fileName);
out.write(bytes);
out.close();
}
3、成果展示