FileUtils.java 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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. * @return
  22. */
  23. public static void setAttachmentResponseHeader(HttpServletResponse response, String realFileName) throws UnsupportedEncodingException {
  24. String percentEncodedFileName = percentEncode(realFileName);
  25. StringBuilder contentDispositionValue = new StringBuilder();
  26. contentDispositionValue.append("attachment; filename=")
  27. .append(percentEncodedFileName)
  28. .append(";")
  29. .append("filename*=")
  30. .append("utf-8''")
  31. .append(percentEncodedFileName);
  32. response.addHeader("Access-Control-Allow-Origin", "*");
  33. response.addHeader("Access-Control-Expose-Headers", "Content-Disposition,download-filename");
  34. response.setHeader("Content-disposition", contentDispositionValue.toString());
  35. response.setHeader("download-filename", percentEncodedFileName);
  36. }
  37. /**
  38. * 百分号编码工具方法
  39. *
  40. * @param s 需要百分号编码的字符串
  41. * @return 百分号编码后的字符串
  42. */
  43. public static String percentEncode(String s) throws UnsupportedEncodingException {
  44. String encode = URLEncoder.encode(s, StandardCharsets.UTF_8.toString());
  45. return encode.replaceAll("\\+", "%20");
  46. }
  47. }