'return ByteArrayResource in spring restcontroller response

I'm trying to download a file using my restController, but it always return this error :

 java.io.FileNotFoundException: Byte array resource [resource loaded from byte array] cannot be resolved to URL
at org.springframework.core.io.AbstractResource.getURL(AbstractResource.java:90) ~[spring-core-4.2.2.RELEASE.jar:4.2.2.RELEASE]

then it downloads a file that has something like this :

  {"byteArray":"JVBERi0xLjQKJeL.... 

here's my restController :

@Api("products")
@RestController
@RequestMapping("/v1/products")
public class DocumentApi extends storeApi {
    @ApiOperation("GET download document")
    @RequestMapping(value = "/temp", method = RequestMethod.GET)
    @ResponseStatus(code = HttpStatus.OK)
    public ResponseEntity<ByteArrayResource> downloadDocument(
        @RequestParam(value = "id", required = true) Long idInscription) throws IOException {
          String signedFilePAth = "C:/APPLIS/signedTemp/5982312957957647037_signed.pdf"
          return ResponseEntity
                 .ok()
                 .contentLength(contentLength)
                 .contentType(
                     MediaType.parseMediaType("application/pdf"))
                 .body(new 
          ByteArrayResource(Files.readAllBytes(Paths.get(signedFilePAth))));
    }
}

and here's my spring configuration :

protected MappingJackson2HttpMessageConverter jacksonMessageConverter() {
    MappingJackson2HttpMessageConverter messageConverter = new MappingJackson2HttpMessageConverter();
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
    // Registering Hibernate4Module to support lazy objects
    mapper.registerModule(new Hibernate4Module());
    messageConverter.setObjectMapper(mapper);
    return messageConverter;
}

public ByteArrayHttpMessageConverter byteArrayHttpMessageConverter() {
    ByteArrayHttpMessageConverter arrayHttpMessageConverter = new ByteArrayHttpMessageConverter();
    arrayHttpMessageConverter.setSupportedMediaTypes(getSupportedMediaTypes());
    return arrayHttpMessageConverter;
}

private List<MediaType> getSupportedMediaTypes() {
    List<MediaType> list = new ArrayList<MediaType>();
    list.add(MediaType.APPLICATION_OCTET_STREAM);
    list.add(MediaType.parseMediaType("application/pdf"));
    return list;
}

@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    converters.add(jacksonMessageConverter());
    converters.add(byteArrayHttpMessageConverter());
    super.configureMessageConverters(converters);
}

what seems to be the problem ? how can i solve this ?

nb : I don't know if this is related, but my swagger-ui.html doesn't work (it shows a blank page) while v2/api-docs/ works fine



Solution 1:[1]

Try returning array of bytes:

@RequestMapping(value = "/temp", method = RequestMethod.GET)
public @ResponseBody byte[] downloadDocument(
        @RequestParam(value = "id", required = true) Long idInscription) throws IOException {
    FileInputStream signedFileInputStream = new FileInputStream(signedFilePAth);
    byte[] doc = IOUtils.toByteArray(fis);
    return doc;
}

IOUtils is from org.apache.commons.io.IOUtils.

Solution 2:[2]

It seems that the response content type definition is missing from your code.

The following code snippet returns with an image content which is displayed by web browser. It is a Jersy code but you can adopt it to Spring:

@GET
@Path("/{image-uuid}")
@Produces("images/jpg")
public Response getImage(@PathParam("uuid") final String uuid) throws IOException {
    byte[] content = imageDao.getImage(uuid);
    if (Objects.isNull(content )) {
        throw new ImageNotFoundError(uuid);
    }

    ByteArrayInputStream stream = new ByteArrayInputStream(content);
    return Response.ok(stream).build();
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Alberto
Solution 2 zappee