介绍前后端分离的文件下载
后台部分(springboot框架)
1.controller层
@RestController
@CrossOrigin
@RequestMapping("/pro")
public class ProController {
@PostMapping("/downloadFile")
@ApiOperation("下载文件")
public ResultVO downloadFile(
HttpServletResponse response) {
return proService.downloadFile(response);
}
}
2.service层
@Override
public ResultVO downloadFile(HttpServletResponse response) {
//逻辑处理和调用文件下载工具类
ToolUtil.downloadFile(response, route);//前端
}
3.工具类
public class ToolUtil {
//下载文件 传入HttpServletResponse对象response 和 文件保存位置path
public static void downloadFile(HttpServletResponse response, String path) {
try {
response.setCharacterEncoding("UTF-8");
//response.setContentType("application/force-download");//应用程序强制下载
File file = new File(path);
//如果文件不存在
if (file == null || !file.exists()) {
String msg = "文件不存在!";
System.out.println(msg);
PrintWriter out = response.getWriter();
out.write(msg);
out.flush();
out.close();
return;
}
String simpleName = file.getName().substring(file.getName().lastIndexOf("/") + 1);
String newFileName = new String(simpleName.getBytes(), "utf-8");
response.setHeader("Content-disposition", "attachment;filename=" + newFileName);
BufferedInputStream bis = new BufferedInputStream(
new FileInputStream(file));
BufferedOutputStream bos = new BufferedOutputStream(
response.getOutputStream());
byte[] buffer = new byte[1024];
int length;
while ((length = bis.read(buffer)) != -1) {
bos.write(buffer, 0, length);
}
if (bis != null)
bis.close();
if (bos != null)
bos.close();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
前台部分
调用这个方法,如果还需要添加其他参数,在form表单添加 <input />即可
function download(){
var $eleForm = $("<form method='post'></form>");
$eleForm.attr("action",https://ip:端口/ + "/pro/downloadFile");
$(document.body).append($eleForm);
$eleForm.submit();
}