从浏览器下载服务器的文件

Demo描述:

浏览器页面展现多个a标签,href属性包含服务器上目标文件的路径。点击a标签,下载相应的文件。

核心代码:

前端代码:

<a href="/download.action?fileURL=F:/test/test.jpg">下载test.jpg</a>

后端代码:

DownloadController.java

package com.lanying.controller;

import com.lanying.util.DownloadUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileNotFoundException;

@Controller
public class DownloadController {

    @RequestMapping(value = "/download")
    @ResponseBody
    public String download(String fileURL, HttpServletRequest req, HttpServletResponse resp){
        boolean isOK = false;
        try {
            isOK = DownloadUtil.download(fileURL, req, resp);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return isOK ? "success!" : "failed!";
    }


}

工具类:

DownloadUtil.java

package com.lanying.util;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLDecoder;
import java.net.URLEncoder;

public class DownloadUtil {

    public static boolean download(String fileURL, HttpServletRequest req, HttpServletResponse resp) throws FileNotFoundException {
        /* Step 1: 入参检查:判空 */
        if(fileURL == null || req == null || resp == null){
            throw new IllegalArgumentException("download方法入参不合法!");
        }

        /* Step 2: 解析fileURL中的中文字符,二选一 */
        // 1) Tomcat安装目录下conf/server.xml中在两个Connector中配置了URIEncoding="UTF-8"
        try {
            fileURL = URLDecoder.decode(fileURL, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        // 2) Tomcat没有配置URIEncoding="UTF-8"
        /*try {
            fileURL = new String(fileURL.getBytes("ISO-8859-1"),"UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }*/

        /* Step 3: 判断服务器端是否存在目标文件 */
        File src = new File(fileURL);

        if(! src.exists()){
            throw new FileNotFoundException(fileURL + "表示的文件不存在!");
        }

        /* Step 4: 设置Headers */
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("application/octet-stream"); // 二进制流,用于文件下载
        String filename = src.getName();
        boolean isMSIE = HttpUtil.isMSBrowser(req);
        try {
            if(isMSIE){
                filename = URLEncoder.encode(filename, "UTF-8"); // 微软旗下的浏览器,用UTF-8编码格式创建文件名
            }else{
                filename = new String(filename.getBytes("UTF-8"),"ISO-8859-1");
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        // 据说可以解决firefox遇到中文空格时截断文件名的问题
        resp.addHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");

        /* Step 5: 文件IO操作(浏览器从服务器下载文件) */
        FileInputStream fis = null;
        OutputStream os = null;

        try {
            fis = new FileInputStream(src);
            os = resp.getOutputStream();

            int len = 0; // 每次读取到缓冲区中的有效字节数
            byte[] buff = new byte[8192]; // 8K缓冲区
            while((len = fis.read(buff)) != -1){
                os.write(buff,0,len);
            }
            return true; // 下载 or 打开成功
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(os != null){
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if(fis != null){
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return false; // 因抛出异常,下载失败
    }
}

HttpUtil.java

package com.lanying.util;

import javax.servlet.http.HttpServletRequest;

public class HttpUtil {
    private static String[] IEBrowserSignals = {"MSIE", "Trident", "Edge"};

    public static boolean isMSBrowser(HttpServletRequest request) {
        String userAgent = request.getHeader("User-Agent");
        for (String signal : IEBrowserSignals) {
            if (userAgent.contains(signal))
                return true; // 是微软旗下的浏览器
        }
        return false; // 其它浏览器
    }
}

参考链接:

https://blog.csdn.net/lanying100/article/details/107313005

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值