如何设置通过 RestController 实现下载文件时的响应标头


public interface IndexApi {
    @ApiOperation(value = "Download excel.", response = byte[].class)
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "The excel file", response = byte[].class),
            @ApiResponse(code = 500, message = "Unexpected error", response = String.class)})
    @GetMapping(
            value = "/api/download",
            produces = {"application/vnd.ms-excel"})
    byte[] download();
}
@RestController
public class TestController implements Api {
        @Override
        public byte[] download() {
            response.setHeader("Content-Disposition", "attachment; filename="somefile.xls"");
            return service.download(symbol);
        }
    }  

当我实现这一点时,它会很好地下载文件,但文件名将被下载。如何设置标题以便自定义文件名?

您可以使用 headerscset 返回一个 ResponseEntity 对象,并将文件流传递给 ResponseEntity

@Override
@ApiOperation(
        value = "Download file.",            
        response = byte[].class)
@ApiResponses(value = {
        @ApiResponse(code = 200, message = "File download.", response = byte[].class),
        @ApiResponse(code = 500, message = "Unexpected error", response = String.class)})
@GetMapping(
        value = "/file/{exDate}/download",
        produces = {"application/vnd.ms-excel"})
public byte[] download(@ApiParam(value = "Valid date.", required = true) @PathVariable(value = "exDate") String exDate, HttpServletResponse response) {
    response.setHeader("Content-disposition", "attachment; filename=" + String.format(FILE_NAME_TEMPLATE, dateArg[0],dateArg[1],dateArg[2]));
    return service.download(exDate);
}

必须将produces参数设置为 application/vnd.ms-excel .

最新更新