chrome Firefox 下载文件名乱码

新手上路,请多包涵

【背景】需求要求从服务器中下载已导出的用户信息Excel表格文件到用户本地
【代码】

   /**
    * 下载生成的所有在线/离线用户信息表格
    * @param request
    * @param response
    * @return 压缩文件
    * @throws FTPConnectionClosedException
    * @throws IOException
    */
   public File downloadExcel (HttpServletRequest request, HttpServletResponse response)
                throws FTPConnectionClosedException, IOException {
    File file = new File(zipPath);
    FileOutputStream fos = new FileOutputStream(file);
    ZipUtils.toZip(path, fos, true);
    //1.获取要下载的文件的绝对路径
    String realPath = zipPath;
    //2.获取要下载的文件名
    String fileName = realPath.substring(realPath.lastIndexOf(File.separator)+1);
    response.reset();
    response.setCharacterEncoding("UTF-8");
    response.setContentType("multipart/form-data");
    //3.设置content-disposition响应头控制浏览器以下载的形式打开文件
    response.addHeader("Content-Disposition","attachment;filename=" + new String(fileName.getBytes(),"utf-8"));
    //获取文件输入流
    InputStream in = new FileInputStream(realPath);
    int len = 0;
    byte[] buffer = new byte[1024];
    OutputStream out = response.getOutputStream();
    while ((len = in.read(buffer)) > 0) {
          //将缓冲区的数据输出到客户端浏览器
        out.write(buffer,0,len);
    }
    in.close();
         return file;
   }

【问题】如何将乱码转换为正常的中文?

clipboard.png

阅读 4.7k
3 个回答
新手上路,请多包涵
新手上路,请多包涵
fileName = URLEncoder.encode(fileName, "UTF-8");
response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
response.setContentType("application/octet-stream;charset=UTF-8");  

换成这样的方式试一下看看。

    response.addHeader("Content-Disposition","attachment;filename=" + new String(fileName.getBytes(),"utf-8"));

utf-8换成iso8859-1试试

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Microsoft
子站问答
访问
宣传栏