zoukankan      html  css  js  c++  java
  • 关于下载远程文件为未知文件.txt的解决方法

    本地下载文件后缀正常,服务器下载文件后缀都为.txt的解决方法:

    后缀为 未知文件.txt 的原因为前端无权限获取Content-Disposition中的文件名

    response.setHeader("content-type", "application/octet-stream");
    response.setContentType("application/octet-stream");
    //将文件名设置到 Content-Disposition
    response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName,"UTF-8"));
    // 这一行一定要加 意为允许前端获取Content-Disposition的文件名 
    response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
    

    下载远程文件代码:

            <dependency>
                <groupId>commons-io</groupId>
                <artifactId>commons-io</artifactId>
                <version>1.3.2</version>
            </dependency>
    

    需引入commons-io使用IOUtils

    此处文件路径例如:http://127.0.0.1:8085/upload/1_1612234092195.jpg

        /**
         * 流下载
         * @param request HttpServletRequest
         * @param response HttpServletResponse
         * @param filePath 文件路径
         */
    public void downloadFile(HttpServletRequest request, HttpServletResponse response, String filePath) {
        OutputStream os = null; //输出流
        try {
            os = response.getOutputStream();
    
            //获取文件名
            String fileName = downloadFileDTO.getFilePath().substring(filePath.lastIndexOf("/")+1);
    
            response.setHeader("content-type", "application/octet-stream");
            response.setContentType("application/octet-stream");
      
    		//将文件名设置到 Content-Disposition
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName,"UTF-8"));
            
            //允许前端获取Content-Disposition中的文件名
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
    
            URL url = new URL (filePath);
            URLConnection uc = url.openConnection();
            IOUtils.copy(uc.getInputStream(), os);
            os.flush();
    
        }catch (Exception e){
            log.error("下载文件失败:{}",e.getMessage());
        }finally {
            try {
                if(os !=null){
                    os.close();
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
    
  • 相关阅读:
    linux(unix)下.tar.gz解压
    linux 实验室
    Liferea 1.0.15
    编造机中鼠标无法应用标题问题解答
    GnuCash 1.9.8
    KDE 走向跨平台, 支持 Windows 和 Mac OS X
    KDVDCreator:创立视频 VCD、SVCD 和 DVD
    digiKam 0.9.3 颁布公布
    Sysinfo 0.7beta4
    KDE 4.1 特性及公布筹划
  • 原文地址:https://www.cnblogs.com/csyzlm/p/14361119.html
Copyright © 2011-2022 走看看