在Spring Rest文件下载调用中,避免使用CoyoteOutputStream对象的签名可以使用以下解决方法:
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StreamUtils;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public ResponseEntity downloadFile() throws IOException {
File file = new File("path/to/file");
FileInputStream fis = new FileInputStream(file);
byte[] fileContent = StreamUtils.copyToByteArray(fis);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
headers.setContentDispositionFormData("attachment", file.getName());
return new ResponseEntity<>(fileContent, headers, HttpStatus.OK);
}
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import java.io.File;
import java.io.IOException;
public ResponseEntity downloadFile() throws IOException {
File file = new File("path/to/file");
FileSystemResource resource = new FileSystemResource(file);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
headers.setContentDispositionFormData("attachment", file.getName());
return ResponseEntity.ok()
.headers(headers)
.contentLength(file.length())
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.body(resource);
}
这两种方法都可以避免在Spring Rest文件下载调用中使用CoyoteOutputStream对象,提供了更简洁和可读性更强的代码。