1、上一章節介紹了spring boot項目實現java上傳,網站鏈接:https://blog.csdn.net/qq_41790332/article/details/102656636。本章主要講解總結spring boot項目中使用java是如何下載文件的。
2、後臺接口代碼(我這裏使用的是通過文件的url進行下載操作)
/**
* 描述:通過id下載所對應的附件
* author:yulin
* Create date 2019-10-13 16:18
*/
@GetMapping("/downByFileId")
@ResponseBody
public void downByFileId(@RequestParam(value="id", required=false) Integer id, HttpServletResponse response,HttpServletRequest request)throws FileNotFoundException, UnsupportedEncodingException {
//通過id查詢獲取到url
File2 file2=fileService.findByFileId( id );
String fileName=file2.getFileTrueName();
try {
URL url = new URL(request.getScheme() + "://" + request.getServerName() +":" + request.getServerPort()+ "/assets/file/" + URLEncoder.encode(file2.getFileTrueName(),"utf-8"));
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
//設置超時間爲3秒
conn.setConnectTimeout(3*1000);
//防止屏蔽程序抓取而返回403錯誤
conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
//得到輸入流
InputStream inputStream=conn.getInputStream();
//獲取自己數組
byte[] bs = readInputStream(inputStream);
/*response.setContentType("application/octet-stream;charset=ISO8859-1");*/
BufferedOutputStream output = null;
String fileNameDown=null;
try {
output = new BufferedOutputStream(response.getOutputStream());
// 中文文件名必須轉碼爲 ISO8859-1,否則爲亂碼
fileNameDown = URLEncoder.encode(fileName, "UTF-8");
response.setContentType("application/force-download");
response.setHeader("Content-Disposition", "attachment;filename=" + fileNameDown);
output.write(bs);
response.flushBuffer();
} catch (Exception e) {
System.out.println( "錯誤" );
} // 用戶可能取消了下載
finally {
if(output!=null){
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 從輸入流中獲取字節數組
* @param inputStream
* @return
* @throws IOException
*/
public static byte[] readInputStream(InputStream inputStream) throws IOException {
byte[] buffer = new byte[1024];
int len = 0;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
while((len = inputStream.read(buffer)) != -1) {
bos.write(buffer, 0, len);
}
bos.close();
return bos.toByteArray();
}
需要注意的是 通過url下載時候需要將url中的中文名進行編碼,要不後臺控制檯就會拋錯。
前臺js:
//下載文件
function download1(a) {
window.open("/downByFileId?id="+a);
}
用windows.open主要是爲了適應微軟自帶的edge瀏覽器,如果使用<a>標籤或者windows.location.href進行打開的話會出現閃退的現象。