How to declare binary data response content-type correctly?

喜夏-厌秋 提交于 2020-12-13 03:28:42

问题


For a web application I am working on, I need to fetch some binary (meta) data for an audio file.

This is how the endpoint looks like:

@RequestMapping(
        value = "/tracks/{trackId}/metadata",
        method = RequestMethod.GET,
        produces = MediaType.APPLICATION_OCTET_STREAM_VALUE
)
@ApiResponse(
        description = "Successful Operation", 
        responseCode = "200", 
        content = @Content(mediaType = MediaType.APPLICATION_OCTET_STREAM_VALUE)
)
public StreamingResponseBody getTrackMetadata(@PathVariable("trackId") Long trackId) {

    TrackEntity track = this.trackService.getTrack(trackId);
    String bucketName = track.getBucketName();
    String bucketFilename = track.getBucketFilename();

    return outputStream -> {

        final int headerSize = 4; // FIXME Get this from file ..

        InputStreamResource inputStreamResource = this.trackService
                .readChunk(bucketName, bucketFilename, 0);

        try (InputStream inputStream = inputStreamResource.getInputStream()) {
            StreamUtils.copyRange(inputStream, outputStream, 0, headerSize);
        }
    };
}

And these are the generated signatures for the endoint:

/**
 * @param trackId
 * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
 * @param reportProgress flag to report request and response progress.
 */
getTrackMetadata(trackId: number, observe?: 'body', reportProgress?: boolean): Observable<any>;
getTrackMetadata(trackId: number, observe?: 'response', reportProgress?: boolean): Observable<HttpResponse<any>>;
getTrackMetadata(trackId: number, observe?: 'events', reportProgress?: boolean): Observable<HttpEvent<any>>;

However, as I try to load the data, I receive a HttpErrorResponse:

Http failure during parsing for https://192.168.178.25:8443/api/tracks/1/metadata

Which reveals that the client tries to parse the data as JSON:

Unexpected token I in JSON at position 0

SyntaxError: Unexpected token I in JSON at position 0↵    at JSON.parse (<anonymous>)
   at XMLHttpRequest.onLoad (https://localhost:4200/vendor.js:30205:51)
   ...

It seems that the generated client code is not aware of the fact that the data is not JSON format.

I have also tried to set content of @ApiResponse to

content = @Content(schema = @Schema(type = "string", format= "byte"))

but the result is the same.

How can I fix this?

来源:https://stackoverflow.com/questions/64080432/how-to-declare-binary-data-response-content-type-correctly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!