Swagger2 如何返回文件内容:使用 @ApiResponses 注解和 MediaType.APPLICATION_OCTET_STREAM
在 Swagger2 中,可以使用 @ApiResponses 注解来定义接口的返回值。如果要返回一个文件,可以使用 MediaType.APPLICATION_OCTET_STREAM_VALUE 作为返回类型,并使用 @ResponseBody 注解将文件内容以字节数组的形式返回。
以下是一个示例:
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
@Controller
@RequestMapping("/file")
public class FileController {
@GetMapping("/download")
@ApiOperation("下载文件")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "OK", response = byte[].class, responseContainer = "ResponseEntity")
})
public @ResponseBody ResponseEntity<byte[]> downloadFile() {
// 从文件系统或其他地方获取文件内容
byte[] fileContent = getFileContent();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
headers.setContentDispositionFormData("attachment", "filename.txt");
return new ResponseEntity<>(fileContent, headers, HttpStatus.OK);
}
private byte[] getFileContent() {
// 从文件系统或其他地方获取文件内容的实现
// ...
}
}
在上述示例中,downloadFile 方法使用 ResponseEntity<byte[]> 作为返回类型,并且使用 MediaType.APPLICATION_OCTET_STREAM 来设置响应的 Content-Type。headers.setContentDispositionFormData('attachment', 'filename.txt') 用于设置响应的文件名。
请注意,上述示例是基于 Spring Boot 和 Spring MVC 的,如果你使用的是其他框架或技术栈,可能会有所不同。
原文地址: https://www.cveoy.top/t/topic/fAs9 著作权归作者所有。请勿转载和采集!