1.前台
按钮
<el-button
size="mini"
icon="el-icon-edit-outline"
type="primary"
@click="fileDownload(scope.row)"
>下载附件</el-button>
方法
fileDownload(row){
window.location.href = "http://localhost:后台端口号/fileDownload/" + row.id ;
},
2.后台
/**
* 下载文件
* @param request
* @param response
* @param id
* @return
* @throws MyException
*/
@RequestMapping(value = "/fileDownload/{id}")
public JsonResult<Object> fileDownload(HttpServletRequest request,HttpServletResponse response,@PathVariable("id") String id) throws Exception{
DeviceSoftware deviceSoftware = deviceSoftwareServiceImpl.getDeviceSoftware(id);//根据文件id从表格中获取该文件的所有信息
if(deviceSoftware!=null){
File file = new File(deviceSoftware.getSwpath());//获取文件存在的地方
//设置返回文件信息
if(file.exists()) {
//可以保存为xls格式的excel文件(兼容老版本)
response.setContentType("application/vnd.ms-excel;charset=UTF-8");
response.setCharacterEncoding("UTF-8");//解决POST乱码
String filename = URLEncoder.encode(file.getName(), "UTF-8");
//设置响应头为文件下载, // 下载文件能正常显示中文
response.setHeader("content-disposition", "attachment;filename="+filename);
response.setContentLength((int)file.length());
int len = 0;
// 实现文件下载
byte []buffer = new byte[1024];
try {
InputStream is = new FileInputStream(file);
OutputStream os= response.getOutputStream();//向浏览器写数据
while((len = is.read(buffer)) != -1){
os.write(buffer,0,len);
}
is.close();
os.close();
System.out.println("Download the song successfully!");
}
catch (Exception e) {
System.out.println("Download the song failed!");
}
}
}
return null; //一定要返回null,执行后不跳转
}