NickJ
NickJ

Reputation: 9579

Spring REST file download from server

I have a Spring REST application, one of the end-points is a download link, where the downloaded file is generated on the fly.

It all works except the filename is wrong.

Here's the relevant parts of the controller:

@RestController
@RequestMapping("/export")
public class ExportREST {

    @RequestMapping(method=RequestMethod.GET)
    public void export(HttpServletResponse response) throws Exception {

        //stuff omitted...
        writeCsvResponse(response);
    }

    private void writeCsvResponse(HttpServletResponse response) throws IOException {
        String fileName = "db.export."+dateFormat.format(new Date());
        response.setContentType( "application/octet-stream" );
        response.setHeader( "Content-Disposition:", "attachment;filename=" + "\"" + fileName + "\"" );

        //write stuff to response...

        response.setContentLength(totalLength);
        response.setBufferSize(1024);
        response.flushBuffer();
        pout.close();
    }
}

So, what I want is a filename with a generated timestamp, but actually the filename is always export, presumably it's getting it from the URL.

Have I missed something?

Upvotes: 2

Views: 1946

Answers (2)

New Wave
New Wave

Reputation: 113

Maybe this help you

  if (mimeType == null) {
        // set to binary type if MIME mapping not found
        mimeType = "application/octet-stream";
    }
    System.out.println("MIME type: " + mimeType);

    // set content attributes for the response
    response.setContentType(mimeType);

More detail servlet in : https://stackoverflow.com/questions/41914092/how-change-servlet-which-download-single-file-but-can-folderfew-files-in-fold

Upvotes: 0

rpozarickij
rpozarickij

Reputation: 1497

There's a colon at the end of "Content-Disposition:". Without it the filename should be picked up.

Upvotes: 3

Related Questions