FileUtils.java 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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 Lion Li
  11. */
  12. public class FileUtils extends FileUtil {
  13. /**
  14. * 下载文件名重新编码
  15. *
  16. * @param response 响应对象
  17. * @param realFileName 真实文件名
  18. * @return
  19. */
  20. public static void setAttachmentResponseHeader(HttpServletResponse response, String realFileName) throws UnsupportedEncodingException {
  21. String percentEncodedFileName = percentEncode(realFileName);
  22. StringBuilder contentDispositionValue = new StringBuilder();
  23. contentDispositionValue.append("attachment; filename=")
  24. .append(percentEncodedFileName)
  25. .append(";")
  26. .append("filename*=")
  27. .append("utf-8''")
  28. .append(percentEncodedFileName);
  29. response.addHeader("Access-Control-Allow-Origin", "*");
  30. response.addHeader("Access-Control-Expose-Headers", "Content-Disposition,download-filename");
  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. String encode = URLEncoder.encode(s, StandardCharsets.UTF_8.toString());
  42. return encode.replaceAll("\\+", "%20");
  43. }
  44. }