FileUtils.java 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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.setHeader("Content-disposition", contentDispositionValue.toString());
  30. response.setHeader("download-filename", percentEncodedFileName);
  31. }
  32. /**
  33. * 百分号编码工具方法
  34. *
  35. * @param s 需要百分号编码的字符串
  36. * @return 百分号编码后的字符串
  37. */
  38. public static String percentEncode(String s) throws UnsupportedEncodingException {
  39. String encode = URLEncoder.encode(s, StandardCharsets.UTF_8.toString());
  40. return encode.replaceAll("\\+", "%20");
  41. }
  42. }