Springboot實現文件的下載與上傳
一.Springboot爲後臺實現下載文件
- 大概思路:從前端獲取一個要下載的文件名後(包含後綴名稱),HttpServletResponse返回一個流文件
- 可能存在的問題:uniapp爲前端的saveFile()方法不支持h5
- 存在跨域問題
- 文件大小的限制
二.上代碼
/**
* 下載文件
* @param name
* @param response
* @return
* @throws UnsupportedEncodingException
*/
@GetMapping("/download/{fileName}")
public CommonReturnType downloadFile(@PathVariable("fileName") String name, HttpServletResponse response) throws UnsupportedEncodingException {
String filePath="E:/fileSource"; //文件的根目錄
File file=new File(filePath+"/"+name); //處理用的文件類,用於操作這個目錄下的文件
if (file.exists()){ //判斷是否存在此文件
response.setContentType("application/vnd.ms-excel;charset=UTF-8");
response.setCharacterEncoding("UTF-8");
response.setHeader("Content-Disposition", "attachment;fileName=" + java.net.URLEncoder.encode(name,"UTF-8")); //爲了下載的東西不亂碼而設置前三個格式
byte[] buffer=new byte[1024]; //每次讀取的最大字節數
FileInputStream fis=null; //建立緩衝輸入字節流
BufferedInputStream bis=null;
OutputStream os=null;
try {
os=response.getOutputStream();//向response緩衝區中寫入字節
fis=new FileInputStream(file);
bis=new BufferedInputStream(fis);
int i=bis.read(buffer); //讀取緩存,若讀不到返回-1
while(i!=-1){
os.write(buffer);
i=bis.read(buffer);
}
}catch (Exception e){
e.printStackTrace();
}
System.out.println("----------file download---" + name);
try{
bis.close(); //關閉流
fis.close();
}catch (IOException e){
e.printStackTrace();
}
return null;
}
return null;
}
三.前端
<a href="http://127.0.0.1:8093/file/download/kaikai.png">下載圖片</a>
- 這裏我直接指定了download下的路徑參數爲kaikai.png是一張圖片
- 通過連接的形式下載東西
通過點擊會出現下載選項,選擇把保存就能保存到本地!