FileUtils.java 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package com.ruoyi.common.utils.file;
  2. import cn.hutool.core.io.FileUtil;
  3. import lombok.AccessLevel;
  4. import lombok.NoArgsConstructor;
  5. import javax.servlet.http.HttpServletResponse;
  6. import java.io.UnsupportedEncodingException;
  7. import java.net.URLEncoder;
  8. import java.nio.charset.StandardCharsets;
  9. /**
  10. * 文件处理工具类
  11. *
  12. * @author Lion Li
  13. */
  14. @NoArgsConstructor(access = AccessLevel.PRIVATE)
  15. public class FileUtils extends FileUtil {
  16. /**
  17. * 下载文件名重新编码
  18. *
  19. * @param response 响应对象
  20. * @param realFileName 真实文件名
  21. */
  22. public static void setAttachmentResponseHeader(HttpServletResponse response, String realFileName) throws UnsupportedEncodingException {
  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.addHeader("Access-Control-Expose-Headers", "Content-Disposition,download-filename");
  32. response.setHeader("Content-disposition", contentDispositionValue.toString());
  33. response.setHeader("download-filename", percentEncodedFileName);
  34. }
  35. /**
  36. * 百分号编码工具方法
  37. *
  38. * @param s 需要百分号编码的字符串
  39. * @return 百分号编码后的字符串
  40. */
  41. public static String percentEncode(String s) throws UnsupportedEncodingException {
  42. String encode = URLEncoder.encode(s, StandardCharsets.UTF_8.toString());
  43. return encode.replaceAll("\\+", "%20");
  44. }
  45. }