1、controller
@GetMapping(value = "/downloadAuditFileByAuditFileId")
public void downloadAuditFileByAuditFileId(@ModelAttribute final GoodNumberAuditInformationDTO auditInformationDTO,
final HttpServletResponse servletResponse) throws IOException {
final GoodNumberAuditInformation auditInformation = goodNumberAuditManagerService.getAuditInformation(auditInformationDTO);
if (Objects.isNull(auditInformation)){
throw new DataNotFoundException("文件数据不存在!");
}
final String attachmentSize = auditInformation.getAttachmentSize();
final String attachmentName = auditInformation.getAttachmentName();
final String attachmentAddress = auditInformation.getAttachmentAddress();
ResponseHeadUtils.setDownloadFileHead(attachmentName, NumberUtils.toInt(attachmentSize), servletResponse);
try (final InputStream inputStream = fileOperationStrategy.getObjectInputStream(auditAttachmentBucketName, attachmentAddress)) {
IOUtils.copy(inputStream, servletResponse.getOutputStream());
} catch (final IOException ioException) {
final String fileId = auditInformation.getAuditId();
log.error("文件下载异常,出现IO异常,下载文件ID是:{}!", fileId, ioException);
throw ioException;
}
}
2、ResponseHeadUtils工具类
import com.mocha.order.constant.ContentTypeConstant;
import com.mocha.order.constant.RequestHeadConstant;
import com.mocha.order.exception.CustomException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.util.UriUtils;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
@Slf4j
public class ResponseHeadUtils {
private ResponseHeadUtils() {}
private static final int MIN_FILE_SIZE = 0;
public static void setContentDisposition(final String fileName, final HttpServletResponse httpServletResponse) {
if (StringUtils.isBlank(fileName)) {
log.error("设置响应头ContentDisposition异常:文件名称为空!");
throw new IllegalArgumentException("文件名称为空!");
}
try {
final String encodedFileName = UriUtils.encode(fileName, StandardCharsets.UTF_8.toString());
httpServletResponse.setHeader(RequestHeadConstant.CONTENT_DISPOSITION,
"attachment; filename=" + encodedFileName + ";filename*=UTF-8''" + encodedFileName);
} catch (final UnsupportedEncodingException e) {
log.error("设置响应头异常:不支持的编码异常!", e);
throw new CustomException("不支持的编码异常!");
}
}
public static void setDownloadFileHead(final String fileName, final int fileSize, final HttpServletResponse httpServletResponse) {
if (fileSize <= MIN_FILE_SIZE) {
log.error("设置响应头ContentLength异常:文件大小为空!");
throw new IllegalArgumentException("文件大小为空!");
}
httpServletResponse.reset();
setContentDisposition(fileName, httpServletResponse);
httpServletResponse.setContentLength(fileSize);
httpServletResponse.setContentType(ContentTypeConstant.APPLICATION_OCTET_STREAM);
}
}
3、前端
/downloadFileById?id=' + id