@Controller
@Slf4j
@RequestMapping("/service/dist")
public class DistributionController {
//下载文件的接口
@GetMapping("/f/{op}/{fakename}")
public void downloadFile(Model model, @PathVariable("op") String op,
@PathVariable("fakename") String fakeName,
HttpServletRequest request, HttpServletResponse response){
String originalName = "";
String fullFilePath = "";
try{
//相对于根目录的相对路径
String storepath = "";
//文件根目录
String fileStoreRootPath= "";
//获取文件
File srcfile=new File(fileStoreRootPath,storepath);
//绝对路径
fullFilePath = srcfile.getPath();
//doDownload方法见https://blog.youkuaiyun.com/daqinzl/article/details/120216664
HttpDownloadUtil.doDownload (request, response, originalName, fullFilePath,"application/pdf", true);
}
catch (Exception e) {
log.error("downloadFile" + originalName + " " + fullFilePath + " " + e.getMessage(),e);
String errMsg = e.getMessage();
}
}
}
--接口调用
String receiveUri = "http://192.168.1.100:7001/service/dist/f/bc9594e5-6e29-4118-b201-dc1c9c72929f/fake";
String tmpPath = "D:/test.xx";
receiveFile(receiveUri, tmpPath);
public void receiveFile( String receiveUri, String tmpPath) {
CloseableHttpClient httpclient = null;
try {
httpclient = HttpClients.custom().build();
HttpEntity entity;
/
HttpGet httpget = new HttpGet(receiveUri);
HttpResponse response1 = null;
try {
response1 = httpclient.execute(httpget); // 用HttpResponse,不用CloseableHttpResponse
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
entity = response1.getEntity();
// System.out.println("get: " + response1.getStatusLine());
///
InputStream is;
try {
is = entity.getContent();
File file = new File(tmpPath);
if (!file.exists()) {
file.createNewFile();
}
OutputStream os = new FileOutputStream(file);
int read = 0;
byte[] temp = new byte[1024 * 1024];
while ((read = is.read(temp)) > 0) {
os.write(temp, 0, read);
}
os.flush();
os.close();
is.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnsupportedOperationException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} finally {
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}