简体   繁体   English

从服务器下载Spring REST文件

[英]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. 我有一个Spring REST应用程序,端点之一是下载链接,下载的文件是在运行时生成的。

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. 因此,我想要的是带有生成时间戳记的文件名,但实际上文件名始终是export ,大概是从URL获取文件名。

Have I missed something? 我错过了什么吗?

There's a colon at the end of "Content-Disposition:". “ 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 有关servlet的更多详细信息, 参见: https : //stackoverflow.com/questions/41914092/how-change-servlet-which-download-single-file-but-can-folderfew-files-in-fold

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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