我的关注 |
¥0.1 java下载文件中文名字乱码
0

java写的下载服务器中,如果下载的文件名是中文,则下载到的文件的名称是乱码。

佛法不二
修改
评论(0)
2个回答
0
采纳

下载文件的代码为:

  1. response.setContentType("text/html; charset=UTF-8");
  2. response.setCharacterEncoding("UTF-8");
  3. FileInputStream fis = null;
  4. BufferedInputStream buff = null;
  5. OutputStream myout = null;
  6. File file = new File(download_file_path + uuid, filename);
  7. try {
  8. if (!file.exists()) {
  9. response.sendError(404, "File not found!!");
  10. return "";
  11. } else {
  12. response.setContentType("APPLICATION/OCTET-STREAM");
  13. response.setContentLength((int) file.length());
  14. response.setHeader("Content-Disposition", "attachment;filename=" + filename);
  15. }
  16. fis = new FileInputStream(file);
  17. buff = new BufferedInputStream(fis);
  18. byte[] b = new byte[1024];
  19. long k = 0;
  20. myout = response.getOutputStream();
  21. while (k < file.length()) {
  22. int j = buff.read(b, 0, 1024);
  23. k += j;
  24. myout.write(b, 0, j);
  25. }
  26. myout.flush();
  27. } catch (IOException e) {
  28. e.printStackTrace();
  29. } finally {
  30. try {
  31. if (fis != null) {
  32. fis.close();
  33. }
  34. if (buff != null)
  35. buff.close();
  36. if (myout != null)
  37. myout.close();
  38. } catch (Exception e) {
  39. e.printStackTrace();
  40. }
  41. }
采纳答案
佛法不二
修改
评论 (0)
0
采纳

是编码问题,对文明名称进入转码即可:

  1. String filename2 = java.net.URLEncoder.encode(filename, "UTF-8");
  2. response.setHeader("Content-Disposition", "attachment;filename=" + filename2);
采纳答案
大智若愚
修改
评论 (0)
撰写回答