前端vue
<div title="点击下载许可文件" style="position:absolute;top: 60px;right: 40px">
<el-link @click="fileUpload">
<a href=" javaScript:;">
//此处是放了一个图片点击下载
<img src="../layui/images/upload.jpg" width="50px" alt="">
</a>
</el-link>
</div>
/文件下载/方法
使用axios无法触及浏览器的下载,所以需要使用下面的方法,
多参数的格式是:window.location.href="/api/xxxx/xxxx?参数1="+canshu1+"&参数2="+canshu2,变量和字符串之间用“+”
fileUpload(){
window.location.href="/api/licenseInfo/fileUpload?
filePath="+this.rightForm.fileuploadPath+"&fileName="+this.rightForm.fileName
},
后台:
controller代码
@ApiOperation("文件下载")
@GetMapping(value = "/fileUpload")
public void fileUpload(HttpServletResponse response, @RequestParam("fileName") String fileName,@RequestParam("filePath") String filePath) throws IOException {
licenseInfoService.fileUpload(response, fileName, filePath);
}
service层代码
//传的filePath是项目的相对路径和文件名称,例如:upload/caichan.xlsx,文件名称是服务器存的随机命名的名称;
fileName是文件的原名称+后缀
public void fileUpload(HttpServletResponse response, String fileName,String filePath) throws IOException {
//获取当前项目的路径,知道项目名的路径
File directory = new File("");// 参数为空
String courseFile = directory.getCanonicalPath();
//根据自己的文件相对路径把,文件名称截取出来
String newName = filePath.substring(7);
//被下载的文件在服务器中的路径,
String downloadFilePath = courseFile + "\\" + "upload" + "\\" + newName;
//查看是否找到了文件
File file = new File(downloadFilePath);
if (file.exists()) {
response.setHeader("content-type", "application/octet-stream");
response.setContentType("application/octet-stream");
try {
//下载时使用源文件的名称
response.setHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode(fileName, "UTF-8"));
} catch (UnsupportedEncodingException e2) {
e2.printStackTrace();
}
byte[] buff = new byte[1024];
BufferedInputStream bis = null;
OutputStream os = null;
try {
os = response.getOutputStream();
bis = new BufferedInputStream(new FileInputStream(file));
int i = bis.read(buff);
while (i != -1) {
os.write(buff, 0, i);
i = bis.read(buff);
}
os.flush();
} catch (FileNotFoundException e1) {
//e1.getMessage()+"系统找不到指定的文件";
// return "系统找不到指定的文件";
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
// return "success";
}
// return "文件未找到";
}