javascrub
javascrub

Reputation: 101

spring file download using ResponseBody

Hello i'm trying create an application allowing me host any kind of file. In order to do it i'm exececuting following magic:

@RequestMapping(value = "/files/{file_name}", method = RequestMethod.GET)
    @ResponseBody
    public FileSystemResource 
    getFile(
            @PathVariable("file_name") String fileName) {
        System.out.println(fileName);
        String filePath = "./files/";
        return new FileSystemResource(new File(filePath+fileName)); 
    }

But this approach brings three unwanted problems:

  1. Some random data is beeing appended to the file

  2. The file gets opened in the browser window instead of beeing downloaded - i've tried to hack this using something like

    produces = "application/octet-stream"

    but it only resulted in 406 error.

  3. The test.txt is beeing truncated into test, i found a walkaround in providing the app with test.txt/ as fileName but it looks a bit messy.

Upvotes: 2

Views: 8215

Answers (2)

StanislavL
StanislavL

Reputation: 57381

I used code like this to return image

@RequestMapping(value = "/image/{id}", method = RequestMethod.GET)
public String getImage(... HttpServletResponse response) {
      response.setContentType(image/png);
      (response.getOutputStream()).write(imageByteArray);
}

I think you have to define proper mime type and send your data to response.

Upvotes: 0

gerrytan
gerrytan

Reputation: 41123

As stated on spring manual

As with @RequestBody, Spring converts the returned object to a response body by using an HttpMessageConverter

I think your problem is spring doesn't come with a HttpMessageConverter than can process FileSystemResource.

A list of builtin HttpMessageConverter is available here. I suggest you try converting your response into byte array somehow, maybe it will pick ByteArrayHttpMessageConverter instead and help solve your issue

Upvotes: 1

Related Questions