vue 实现文件下载

这篇博客介绍了如何在前端使用Element UI组件实现下载附件的功能,通过点击按钮触发文件下载。点击事件调用`fileDownload`方法,将请求发送到后台指定URL。后台接收到请求后,通过文件ID获取文件信息,设置响应头并读取文件内容,以流的形式将文件发送回前端,完成下载。整个过程涉及到HTTP响应头的设置、文件流的处理以及文件路径的获取。
摘要由CSDN通过智能技术生成

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,执行后不跳转
	}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue实现PDF文件下载非常简单,只需要通过Vue的axios库向后端发送请求获取二进制PDF文件的数据流,然后将其转换为Blob对象,并使用URL.createObjectURL()将其转换为可下载的URL,接着再使用a标签的download属性实现下载即可。 具体实现如下: 1.安装axios库 npm install axios --save 2.在Vue组件中引入axios和FileSaver库 import axios from 'axios'; import FileSaver from 'file-saver'; 3.在Vue组件方法中实现PDF文件下载 downloadFile() { axios.get('http://localhost:8080/api/download/pdf', { responseType: 'arraybuffer' }) .then(response => { const blob = new Blob([response.data], { type: 'application/pdf' }); const fileName = 'test.pdf'; FileSaver.saveAs(blob, fileName); }) .catch(error => { console.error('Error downloading PDF file', error); }); } 4.在后端实现返回二进制PDF文件的接口 @RequestMapping(value = "/download/pdf", method = RequestMethod.GET) @ResponseBody public ResponseEntity<byte[]> downloadPDF() throws IOException { File file = new File("test.pdf"); byte[] bytes = FileUtils.readFileToByteArray(file); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_PDF); headers.setContentDispositionFormData("attachment", "test.pdf"); headers.setContentLength(bytes.length); return new ResponseEntity<byte[]>(bytes, headers, HttpStatus.OK); } 以上是Vue实现PDF文件下载的简单示例,可以通过修改接口地址和文件名来适应不同的场景。同时,需要注意的是该方法需要在前端启动了服务器的情况下才能正常使用。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值