• Java文件下载,Java通用文件下载,Java文件下载中文乱码


    ================================

    ©Copyright 蕃薯耀 2020-01-07

    https://www.cnblogs.com/fanshuyao/

    import java.io.BufferedInputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.net.URLDecoder;
    import java.util.ArrayList;
    import java.util.Date;
    import java.util.HashMap;
    import java.util.Iterator;
    import java.util.List;
    import java.util.Map;
    import java.util.UUID;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import org.apache.commons.io.FileUtils;
    import org.apache.commons.lang.StringUtils;
    import org.apache.log4j.Logger;
    import org.springframework.util.FileCopyUtils;
    import org.springframework.web.multipart.MultipartFile;
    import org.springframework.web.multipart.MultipartHttpServletRequest;
    import org.springframework.web.multipart.commons.CommonsMultipartResolver;
    
    
    
    public class FileAction extends BaseAction{
    
        private Logger log = Logger.getLogger(FileAction.class);
        
        
        /**
         * 通用文件下载方法
         * @param request HttpServletRequest
         * @param response HttpServletResponse
         * @param absoluteFilePath String 文件的绝对路径,如:c:/a/a.txt
         * @param fileDownloadName String 自定义文件下载显示的名称
         * @param isDeleteAfterDownload boolean 用户下载文件后是否删除服务器的源文件,true删除,其它否
         */
        public void downloadFile(HttpServletRequest request, HttpServletResponse response, 
                String absoluteFilePath, String fileDownloadName, boolean isDeleteAfterDownload){
            InputStream is = null;
            OutputStream os = null;
            File file = null;
            try{
                log.info("开始时间:"+System.currentTimeMillis());
                
                
                file = new File(absoluteFilePath);
                if(!file.exists()){
                    throw new RuntimeException("文件不存在:"+file.getAbsolutePath());
                }
                is = new BufferedInputStream(new FileInputStream(file));
                
                String suffix = absoluteFilePath.substring(absoluteFilePath.lastIndexOf("."));
                if(".xls".equalsIgnoreCase(suffix) || ".xlsx".equalsIgnoreCase(suffix)){
                    response.setContentType("application/vnd.ms-excel");
                }else if(".doc".equalsIgnoreCase(suffix) || ".docx".equalsIgnoreCase(suffix)){
                    response.setContentType("application/vnd.msword");
                }else if(".exe".equalsIgnoreCase(suffix)){
                    response.setContentType("application/octet-stream");
                }else if(".jpe".equalsIgnoreCase(suffix) || ".jpeg".equalsIgnoreCase(suffix) || ".jpg".equalsIgnoreCase(suffix)){
                    response.setContentType("image/jpeg");
                }else if(".png".equalsIgnoreCase(suffix)){
                    response.setContentType("image/png");
                }else if(".gif".equalsIgnoreCase(suffix)){
                    response.setContentType("image/gif");
                }else if(".mp3".equalsIgnoreCase(suffix)){
                    response.setContentType("audio/x-mpeg");
                }else if(".mp4".equalsIgnoreCase(suffix) || ".mpg4".equalsIgnoreCase(suffix)){
                    response.setContentType("video/mp4");
                }else if(".wm".equalsIgnoreCase(suffix)){
                    response.setContentType("video/x-ms-wm");
                }else if(".wmv".equalsIgnoreCase(suffix)){
                    response.setContentType("audio/x-ms-wmv");
                }else if(".rm".equalsIgnoreCase(suffix) || ".rmvb".equalsIgnoreCase(suffix)){
                    response.setContentType("audio/x-pn-realaudio");
                }else if(".xml".equalsIgnoreCase(suffix)){
                    response.setContentType("text/xml");
                }else if(".gz".equalsIgnoreCase(suffix)){
                    response.setContentType("application/x-gzip");
                }else if(".gtar".equalsIgnoreCase(suffix)){
                    response.setContentType("application/x-gtar");
                }else if(".tar".equalsIgnoreCase(suffix) || ".taz".equalsIgnoreCase(suffix)){
                    response.setContentType("application/x-tar");
                }else if(".rar".equalsIgnoreCase(suffix)){
                    response.setContentType("application/x-rar-compressed");
                }else if(".zip".equalsIgnoreCase(suffix)){
                    response.setContentType("application/zip");
                }else{
                    response.setContentType("multipart/form-data");
                }
                
                //处理自定义文件名,如果自定义文件名,使用原来的文件名进行下载
                if(StringUtils.isBlank(fileDownloadName)){//org.apache.commons.lang.StringUtils
                    fileDownloadName = file.getName().substring(0, file.getName().lastIndexOf("."));;
                }else{
                    if(fileDownloadName.indexOf(".") > -1){
                        fileDownloadName = fileDownloadName.substring(0, fileDownloadName.lastIndexOf("."));
                    }
                }
                
                //文件名编码,解决中文乱码问题
                String userAgent = request.getHeader("User-Agent").toLowerCase();
                if(userAgent.contains("msie") 
                        || userAgent.contains("trident") 
                        || userAgent.contains("edge")){//IE浏览器
                    
                    fileDownloadName = URLEncoder.encode(fileDownloadName, "UTF-8");
                    fileDownloadName = fileDownloadName.replaceAll("\+", "%20");//处理文件名多余的加号(+)
                }else{//其它浏览器
                    fileDownloadName = new String(fileDownloadName.getBytes("UTF-8"), "ISO-8859-1");
                }
                
                response.setCharacterEncoding("UTF-8");
                response.addHeader("Content-Disposition", "attachment;filename="" + fileDownloadName + suffix + """);
                response.addHeader("Content-Length", "" + file.length());
                
                os = response.getOutputStream();
                
                byte[] buffer = new byte[1024];
                int length = 0;
                while((length = is.read(buffer)) > 0){
                    os.write(buffer, 0, length);
                }
                log.info("结束时间:"+System.currentTimeMillis());
            }catch(Exception e){
                e.printStackTrace();
                log.info("下载文件出错:"+e.getCause());
            }finally{
                try {
                    if(os != null){
                        //os.flush();
                        os.close();
                    }
                    if(is != null){
                        is.close();
                    }
                    if(isDeleteAfterDownload){
                        if(file != null){
                            //org.apache.commons.io.FileUtils
                            FileUtils.deleteQuietly(file);
                        }
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }
        
        
    }

    (如果你觉得文章对你有帮助,欢迎捐赠,^_^,谢谢!) 

    ================================

    ©Copyright 蕃薯耀 2020-01-07

    https://www.cnblogs.com/fanshuyao/

  • 相关阅读:
    day10 基本数据类型介绍-整形的魔法
    python 快捷键
    F5负载均衡 简要原理解析以及命令行命令
    Python之路(2)
    Pycharm的安装
    集合框架(Collection和Collections的区别)
    集合框架(04)HashMap扩展知识
    集合框架(04)HashMap
    集合框架(03)泛型
    MVC
  • 原文地址:https://www.cnblogs.com/fanshuyao/p/12159739.html
Copyright © 2020-2023  润新知