Uploading file from Spring Rest Controller

I am trying to upload a file via Spring REST Controller. Below is my code -

@RequestMapping(value="/aaa",method=RequestMethod.GET,produces=MediaType.APPLICATION_OCTATE_STREAM_VALUE) 
public ResponseEntity<byte[]> testMethod(@RequestParam("test") String test) {
    HttpHeaders responseHeaders = new HttpHeaders();
    responseHeaders.setContentDispositionFromData("attachment","testExcel.xlsx");
    responseHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
    File file = new File("C:\\testExcel.xlsx");
    Path path = Paths.get(file.getAbsolutePath());
    ByteArrayResource resource = new ByteArrayResource(Files.readAllbytes(path));
    return new ResposeEntity<byte[]>(resource.getByteArray(),responseHeaders,HttpStatus.OK);
}

      

This is called by clicking a button. After pressing the button, nothing happens. By debugging this java I could see the byte stream. In Mozilla developer tools, I could see a successful HTTP response (response in bytes of this excel file). According to the resources available on the internet, the browser should automatically download the file, but it doesn't.

Why is loading not happening in the browser? What else do I need to do to make it work?

NOTE. It's just for POC purpose. Currently I have to generate excel file from database data, via Apache POI or some other API.

+3


source to share


3 answers


Below works for me:



@RequestMapping("/")
public void index(HttpServletRequest request, HttpServletResponse response) throws IOException {

    FileInputStream inputStream = new FileInputStream(new File("C:\\work\\boot\\pom.xml"));

    response.setHeader("Content-Disposition", "attachment; filename=\"testExcel.xlsx\"");
    response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);

    ServletOutputStream outputStream = response.getOutputStream();
    IOUtils.copy(inputStream, outputStream);

    outputStream.close();
    inputStream.close();
}

      

+1


source


In my case, it worked like this for the server to send the following header:

Access-Control-Expose-Headers: Content-Disposition

      



So my problem was related to CSRF issue.

0


source


Change the code as follows:

public HttpEntity<byte[]> testMethod(@RequestParam("test") String test) {

    File file = new File("C:\\testExcel.xlsx");
    FileInputStream fileInputStream = new FileInputStream(file);
    byte[] array = IOUtils.toByteArray(fileInputStream);

    HttpHeaders header = new HttpHeaders();
    header.set("Content-type","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
    header.set("Content-Disposition", "attachment; filename=" + nameyouwantsaveyourfile + ".xlsx");
    header.setContentLength(array.length);
    fileInputStream.close();
    return new HttpEntity<byte[]>(array, header);
}

      

0


source







All Articles