FileUtils.java 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package com.ruoyi.common.utils.file;
  2. import cn.hutool.core.io.FileUtil;
  3. import javax.servlet.http.HttpServletResponse;
  4. import java.io.UnsupportedEncodingException;
  5. import java.net.URLEncoder;
  6. import java.nio.charset.StandardCharsets;
  7. /**
  8. * 文件处理工具类
  9. *
  10. * @author ruoyi
  11. */
  12. public class FileUtils extends FileUtil
  13. {
  14. /**
  15. * 下载文件名重新编码
  16. *
  17. * @param response 响应对象
  18. * @param realFileName 真实文件名
  19. * @return
  20. */
  21. public static void setAttachmentResponseHeader(HttpServletResponse response, String realFileName) throws UnsupportedEncodingException
  22. {
  23. String percentEncodedFileName = percentEncode(realFileName);
  24. StringBuilder contentDispositionValue = new StringBuilder();
  25. contentDispositionValue.append("attachment; filename=")
  26. .append(percentEncodedFileName)
  27. .append(";")
  28. .append("filename*=")
  29. .append("utf-8''")
  30. .append(percentEncodedFileName);
  31. response.setHeader("Content-disposition", contentDispositionValue.toString());
  32. response.setHeader("download-filename", percentEncodedFileName);
  33. }
  34. /**
  35. * 百分号编码工具方法
  36. *
  37. * @param s 需要百分号编码的字符串
  38. * @return 百分号编码后的字符串
  39. */
  40. public static String percentEncode(String s) throws UnsupportedEncodingException
  41. {
  42. String encode = URLEncoder.encode(s, StandardCharsets.UTF_8.toString());
  43. return encode.replaceAll("\\+", "%20");
  44. }
  45. }