SpringBoot中实现文件的下载--下载指定路径下的文件

代码参考如下:
一、接收页面下载的请求(后台Controller方法)

	/**
	 * 	文件下载
	 * @param response
	 * @param fId
	 * @return
	 */
	@RequestMapping("/down")
	@CrossOrigin(origins = "*", methods = {RequestMethod.GET, RequestMethod.POST})
    public String down(HttpServletResponse response,String fId) {
        try {
        	//根据文件id查询文件路径
        	FileInfo fileInfo=fileService.getFileVersion(fId);
			//根据文件路径下载文件信息
        	UploadUtil.down(response, fileInfo.getfPath());
			
			return "下载成功";
        } catch (IOException e) {
        	e.printStackTrace();
        }
        return "下载失败";
    }

二、代码中下载的工具类方法

/**
     * 下载
     * 由于HTTP头部的默认编码为ISO-8859-1而我们上传文件于下载文件过程中,提取到的文件名都要通过HTTP头部。
     *所以我们需要在上传的时候对提取到的文件名进行转码为UTF-8,然后在下载时我们也要进行反向转码为ISO-8859-1.
     * @param res
     * @param pathAddress
     */
    public static void down(HttpServletResponse res,String pathAddress) throws UnsupportedEncodingException {
        File file=new File(pathAddress);
        String fileName = file.getName();
        
        res.setHeader("content-type", "application/octet-stream");
        res.setContentType("application/octet-stream");
        res.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("utf-8"),"iso-8859-1"));
        
        byte[] buff = new byte[1024];
        FileInputStream bis = null;
        OutputStream os = null;
        try {
            os = res.getOutputStream();
            bis = new FileInputStream(file);
            int readTmp = 0;
			while ((readTmp = bis.read(buff)) != -1) {
			//并不是每次都能读到1024个字节,所有用readTmp作为每次读取数据	的长度,否则会出现文件损坏的错误
				os.write(buff, 0, readTmp);
				
			}
			
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bis != null) try {
                bis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        System.out.println("success");
    }
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Monika、

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值