0

I cannot find out why the mp3 file is different after download from my server than original one saved previously there.

This is my controller method. The content of file (byte[] content) is identical with original file on this stage - the original file is the same as file retrieved from database (checked in debugger).

    @ResponseBody
    @RequestMapping(method = RequestMethod.GET, value = "/{sampleId}/file")
    public HttpEntity<byte[]> getFile(@PathVariable Long sampleId) {
        ResourceEntity resourceEntity = testSampleRepository.getFile(sampleId);
        byte[] content = resourceEntity.getContent();
        String fileName = resourceEntity.getFileName();
        HttpHeaders header = new HttpHeaders();
        header.setContentType(new MediaType("audio", "mpeg"));
        header.set(HttpHeaders.CONTENT_DISPOSITION,
                "attachment; filename=" + fileName.replace(" ", "_"));
        header.setContentLength(content.length);
        return new HttpEntity<byte[]>(content, header);
    }

This is how files differ (the left is original one): enter image description here

Why passing using HTTP distors my file? Should mediaTypes enforce certain encoding? (there was no difference with "audio/mpeg" mediaType and without it).

Mcmil
  • 795
  • 9
  • 25
  • I think your media type is wrong, try audio/mpeg3, https://www.sitepoint.com/web-foundations/mime-types-complete-list/ – Chirdeep Tomar Jan 03 '17 at 01:46
  • 4
    You need to show the code that downloads the file, and you need to say which one is the original and which one is the downloaded one. From the looks of it, the right file contains ASCII-only characters so it may be base64-encoded (although that would be unnecessary over an HTTP connection) – Erwin Bolwidt Jan 03 '17 at 01:46
  • @ErwinBolwidt Base64 could have been from the FORM POST `multipart/form-data` upload. – Andreas Jan 03 '17 at 02:03
  • That's right - spring encoded content to Base64. After decode files are the same. – Mcmil Jan 03 '17 at 12:17

1 Answers1

2

It should work, if you set the produces = "application/octet-stream" attribute (MediaType.APPLICATION_OCTET_STREAM). Otherwise, you are trapped by Spring's converter framework.

You may want to have a look here, seems your problem is very similar: Spring MVC: How to return image in @ResponseBody? .

Community
  • 1
  • 1
thst
  • 4,592
  • 1
  • 26
  • 40
  • Thank you. I am getting strange exception after add produces with @ResponseBody and without it, i.e: HttpMediaTypeNotAcceptableException: Could not find acceptable representation. – Mcmil Jan 03 '17 at 12:20
  • Solved HttpMediaTypeNotAcceptableException: Need to use simple Controller/RestController instead of RepositoryRestController (customizing Spring Data Rest repository). – Mcmil Jan 03 '17 at 12:44