以下是一个比较完整的流程
后端代码如下:
controller:
@RequestMapping(value = "/download", method = RequestMethod.GET)public String downloadData(HttpServletResponse res) { String data="这是一个下载文件"; //传入数据 File file=new File("文件.txt"); FileUtils.getFile(data.getBytes(),file.getName()); FileUtils.responseTo(file,res); file.delete(); System.out.println("success"); return "success";}复制代码
工具类如下:
public class FileUtils {public static void getFile(byte[] bfile, String fileName) { //创建文件 File file=new File(fileName); try { if (!file.exists()){file.createNewFile();} FileOutputStream fos = new FileOutputStream(file); fos.write(bfile); } catch (Exception e) { e.printStackTrace(); }}public static void responseTo(File file, HttpServletResponse res) { //将文件发送到前端 res.setHeader("content-type", "application/octet-stream"); res.setContentType("application/octet-stream"); res.setHeader("Content-Disposition", "attachment;filename=" + file.getName()); byte[] buff = new byte[1024]; BufferedInputStream bis = null; OutputStream os = null; try { os = res.getOutputStream(); bis = new BufferedInputStream(new FileInputStream(file)); int i = bis.read(buff); while (i != -1) { os.write(buff, 0, buff.length); os.flush(); i = bis.read(buff); } } catch (IOException e) { e.printStackTrace(); } finally { if (bis != null) { try { bis.close(); } catch (IOException e) { e.printStackTrace(); } } } System.out.println("success");}}复制代码
前端文件接收:
axios({ url: '/gafzpt/capital/download', method: 'get', params: { capitalId: capitalId }, responseType: 'blob' //接收类型设置,否者返回字符型 }) .then(res => { //定义文件名等相关信息 const blob = res.data const reader = new FileReader() reader.readAsDataURL(blob) reader.onload = (e) => { const a = document.createElement('a') a.download = `现金流文件` a.href = e.target.result document.body.appendChild(a) a.click() document.body.removeChild(a) } })复制代码