java文件下载,解决IE、FireFox、Chrome、Safari相关问题,返回下载流有接收端解析(浏览器或者别的接收端)

版权声明: https://blog.csdn.net/Soul_Programmer_Swh/article/details/81773781
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Collection;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.thunisoft.artery.util.ArteryUtil;
import com.thunisoft.export15xml.ConfigManager;

import eu.medsea.mimeutil.MimeType;
import eu.medsea.mimeutil.MimeUtil;

public class DownloadData extends HttpServlet {

    private static final long serialVersionUID = 1L;

    private ConfigManager configManager;

    private static Logger logger = LoggerFactory.getLogger(DownloadData.class);

    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
    }

    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws IOException {
        configManager = (ConfigManager) ArteryUtil.getBean("configManager");
        String fileName = request.getParameter("fileName");
        String path = configManager.getConfig("config.downloadUrl") + fileName;

        if (logger.isDebugEnabled()) {
            logger.debug("下载文件:" + fileName);
        }

        if (StringUtils.isBlank(fileName)) {
            fileName = "unkown";
        }

        Collection<?> mimeList = MimeUtil.getMimeTypes(fileName);
        MimeType mimeType = (MimeType) mimeList.iterator().next();
        String contentType = mimeType.toString();

        //        response.setCharacterEncoding("UTF-8");
        response.setContentType(contentType);

        String encodedName = null;
        String userAgent = request.getHeader("User-Agent");
        if (StringUtils.isBlank(userAgent)) {
            encodedName = URLEncoder.encode(fileName, "UTF-8");
            encodedName = encodedName.replaceAll("\\+", "%20");
        } else {
            boolean isIE = false;
            if (userAgent.indexOf("MSIE") != -1) {
                isIE = true;
            } else if (userAgent.indexOf("Trident") != -1) {
                isIE = true;
            } else if (StringUtils.contains(userAgent, "Edge")) {
                isIE = true;
            }
            if (isIE) {
                // IE使用URLEncoder
                encodedName = URLEncoder.encode(fileName, "UTF-8");
                encodedName = encodedName.replaceAll("\\+", "%20"); // 解决IE下载时,文件名中空格变加号的问题
            } else {
                // FireFox、chrome、Safari使用ISO-8859-1
                encodedName = new String(fileName.getBytes("UTF-8"),
                        "ISO-8859-1");
            }
        }
        response.setHeader("Content-disposition", "attachment;filename=\""
                + encodedName + "\""); // 加引号是解决Firefox下载时,文件名中空格及之后的部分被截断的问题
        response.setHeader("Cache-Control",
            "must-revalidate, post-check=0, pre-check=0");
        response.setHeader("Pragma", "public");
        response.setDateHeader("Expires", (System.currentTimeMillis() + 1000));

        FileInputStream fileInput = new FileInputStream(path);
        OutputStream os = response.getOutputStream();
        try {
            byte[] data = new byte[8192];
            int count = 0;
            while ((count = fileInput.read(data)) != -1) {
                os.write(data, 0, count);
            }
            os.flush();
        } finally {
            if (fileInput != null) {
                try {
                    fileInput.close();
                } catch (Exception e) {
                    logger.error("关闭流异常");
                }
            }
        }
    }
}

 

阅读更多

扫码向博主提问

soul_programmer_swh

非学,无以致疑;非问,无以广识
  • 擅长领域:
  • Java
  • Spring
  • Database
  • 编程思想
去开通我的Chat快问
换一批

没有更多推荐了,返回首页