package com.bonus.file.utils;

import com.bonus.common.core.constant.HttpStatus;
import com.bonus.common.core.utils.StringUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

public class FileUtils {
/**
* 获取文件名
 */
  public static String setResponseHeaderByUrl(HttpServletResponse response,  String url) {
      String safeFileName = com.bonus.common.core.utils.file.FileUtils.getName(url);
      if (!StringUtils.hasText(safeFileName)) {
          response.setStatus(HttpStatus.BAD_REQUEST);
          return null;
      }
      try {
          String encodedFileName = URLEncoder.encode(safeFileName, StandardCharsets.UTF_8.toString());
          if (encodedFileName == null) {
              response.setStatus(HttpStatus.BAD_REQUEST);
              return null;
          }
          response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
          response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + encodedFileName + "\"");
          return encodedFileName;

      } catch (UnsupportedEncodingException e) {
          response.setStatus(HttpStatus.BAD_REQUEST);
          return null;
      }
  }
}
