- 通过文件名,获取文件
- 远程调用接口拿到文件的
byte[]
后再处理进行返回文件给前端页面
调用方接口
@RequestMapping("/download")
public void download(String filename, HttpServletRequest request, HttpServletResponse response) {
try {
if (StringUtils.isNotBlank(filename)) {
byte[] bs = localStoreDirConfig.getFileInputStreamByExport(filename);
if (bs != null){
try (ServletOutputStream os = response.getOutputStream()){
String extendFileName = FileUtil.getSuffix(filename);
response.setContentType(request.getSession().getServletContext().getMimeType(extendFileName));
response.setHeader("content-disposition","attachment;fileName="+ URLEncoder.encode("交互回复记录.xlsx","UTF-8"));
os.write(bs);
os.flush();
}catch (Exception e){
log.error("异常",e);
}
}
}
} catch (Exception e) {
log.error("下载文件异常",e);
}
}
public byte[] getFileInputStreamByExport(String fileName) throws Exception{
return getBytes(fileName,"byExport");
}
yml
自定义了其他应用的地址,这里进行遍历逐个寻找
private byte[] getBytes(String fileName,String by) throws Exception{
String dir = by.equals("byImport") ?uploadFileStoreDir:exportFileStoreDir + "/";
File localFile = new File(dir + fileName);
if (localFile.exists() && localFile.isFile()){
try (
FileInputStream fis = new FileInputStream(localFile);
ByteArrayOutputStream baos = new ByteArrayOutputStream()
){
byte[] bytes = new byte[2048];
int length;
while ((length = fis.read(bytes)) != -1) {
baos.write(bytes, 0 ,length);
}
return baos.toByteArray();
}
}
for (BossServer server : otherBossServerConfig.otherBossProperties().getServers()) {
String url = String.format("http://%s:%s/remote/getFile/%s/%s", server.getIp(), server.getPort(), by,fileName);
try {
try (HttpResponse resp = HttpRequest.post(url).timeout(30*1000).execute()) {
log.info("callRemoteSyncApi url:{} | by:{} | fileName:{} | resp sta:{}",url,by, fileName, resp.getStatus());
byte[] bs = resp.bodyBytes();
if (bs != null){
try (FileOutputStream f = new FileOutputStream(dir + fileName)){
f.write(bs);
f.flush();
}catch (Exception e){
log.error("远程获取的文件,懒备份到本地 localPath:{} | fileName:{} | by:{}",dir,fileName,by);
}
return bs;
}
}catch (Exception e){
log.info("callRemoteSyncApi 异常 url:{} | by:{} | fileName:{}",url,by, fileName,e);
}
} catch (Exception e) {
log.info("callRemoteSyncApi 异常 url:{}", url, e);
}
}
return null;
}
被调用方远程接口
@PostMapping("/getFile/{from}/{fileName}")
public void getFile(@PathVariable("from") String from, @PathVariable("fileName") String fileName, HttpServletResponse response) throws Exception{
byte[] bs = null;
bs = localStoreDirConfig.getFileInputStreamByExport(fileName);
if (bs != null && bs.length >0){
try (ServletOutputStream ops = response.getOutputStream()){
ops.write(bs);
ops.flush();
}
}
}
public byte[] getFileInputStreamByExport(String fileName) throws Exception{
return getBytes(fileName,"byExport");
}