简体   繁体   中英

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM