通过a标签请求后台下载文件

	/**
	 *<下载>
	 *@param url 文件网络路径
	 *@return
	 *@creater Leo
	 *@datetime 2018年11月19日
	 */	
    @RequestMapping(value="dowmloadFile")
	@ResponseBody
	public void dowmloadFile(@RequestParam("url")String url,HttpServletRequest request,HttpServletResponse response){
		ServletOutputStream out = null;  
        InputStream ips = null;  
        URL oracle = null;
        try {
			oracle = new URL(url);
		} catch (MalformedURLException e1) {
			e1.printStackTrace();
			 return ; 
		}
        HttpURLConnection uc = null;
		try {
			uc = (HttpURLConnection) oracle.openConnection();
		} catch (IOException e1) {
			e1.printStackTrace();
			return ; 
		} 
	    try {  
	          uc.setDoInput(true);//设置是否要从 URL 连接读取数据,默认为true  
	          uc.connect(); 
	            //文件名
	            String newFileName = fileName(url);
	            ips =  uc.getInputStream();  
	            response.setContentType("multipart/form-data"); 
                        //为文件重新设置名字,采用数据库内存储的文件名称 
	            response.addHeader("Content-Disposition", "attachment; filename=\"" + new String(newFileName.getBytes("UTF-8"),"ISO8859-1") + "\"");
	            out = response.getOutputStream();  
	            //读取文件流  
	            int len = 0;  
	            byte[] buffer = new byte[1024 * 10];  
	            while ((len = ips.read(buffer)) != -1){  
	                out.write(buffer,0,len);  
	            }  
	            out.flush();  
	        }catch (Exception e){  
	            e.printStackTrace();  
	        }finally {  
	            try {
					out.close();
					ips.close();  
				} catch (IOException e) {
					e.printStackTrace();
				}  
	        }  
        return ; 
	}
	
	/**
	 *<文件名获取>
	 *@param fileName
	 *@return
	 *@creater Leo
	 *@datetime 2018年11月19日
	 */
	private String fileName(String fileName){
		String ext = Strings.EMPTY;
		if (Strings.isNotBlank(fileName)) {
			int offset = fileName.lastIndexOf("/");
			if (offset != -1 && offset != fileName.length() - 1) {
				ext = fileName.substring(offset + 1);
			}
		}
		return ext.toLowerCase();
	}

前台写个<a href="请求路径">

在前端使用Vue发送请求下载PDF文件需要用到两个技术:axios和Blob。 首先,在Vue项目中安装axios: ``` npm install axios --save ``` 然后,在Vue组件中使用axios发送请求下载PDF文件: ```javascript import axios from 'axios' export default { methods: { downloadPDF() { axios({ url: 'your-backend-api', method: 'GET', responseType: 'blob' // 返回类型为blob }).then(response => { const url = window.URL.createObjectURL(new Blob([response.data])) const link = document.createElement('a') link.href = url link.setAttribute('download', 'file.pdf') // 下载文件名 document.body.appendChild(link) link.click() }) } } } ``` 在代码中,我们设置了axios的请求类型为'GET',返回类型为'blob'。当请求成功时,我们将response.data转换为Blob类型,创建URL并生成一个a标签用于下载。将a标签添加到body中,模拟用户点击下载。最后,我们需要注意设置下载文件文件名。 在后端,你需要设置响应头的Content-Type为'application/pdf',推荐使用node.js的mime模块来获取正确的Content-Type: ```javascript const fs = require('fs') const path = require('path') const mime = require('mime') app.get('/download', (req, res) => { const filePath = path.join(__dirname, 'file.pdf') const fileStream = fs.createReadStream(filePath) const contentType = mime.getType(filePath) res.setHeader('Content-Type', contentType) res.setHeader('Content-Disposition', 'attachment; filename=file.pdf') fileStream.pipe(res) }) ``` 在代码中,我们使用fs模块读取文件流,使用mime模块获取正确的Content-Type并设置响应头。最后,将文件流通过管道pipe到响应中,完成下载
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值