程序问答   发布时间:2022-06-02  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了从Spring Boot Rest服务下载文件大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决从Spring Boot Rest服务下载文件?

开发过程中遇到从Spring Boot Rest服务下载文件的问题如何解决?下面主要结合日常开发的经验,给出你关于从Spring Boot Rest服务下载文件的解决方法建议,希望对你解决从Spring Boot Rest服务下载文件有所启发或帮助;

仅当没有其他特定的资源实现适用时才应使用。特别是,尽可能选择ByteArrayresource或任何基于文件的resource实现。

@requestMapPing(path = "/download", method = requestMethod.GET)
public ResponseEntity<resource> download(String param) throws IOException {

    // ...

    inputStreamresource resource = new inputStreamresource(new fileinputStream(filE));

    return ResponseEntity.ok()
            .headers(headers)
            .contentLength(file.length())
            .ContentType(MediaType.parseMediaType("application/octet-stream"))
            .body(resourcE);
}

Option2作为inputStreamresource的文档建议-使用ByteArrayresource:

@requestMapPing(path = "/download", method = requestMethod.GET)
public ResponseEntity<resource> download(String param) throws IOException {

    // ...

    Path path = Paths.get(file.getabsolutePath());
    ByteArrayresource resource = new ByteArrayresource(files.readAllBytes(path));

    return ResponseEntity.ok()
            .headers(headers)
            .contentLength(file.length())
            .ContentType(MediaType.parseMediaType("application/octet-stream"))
            .body(resourcE);
}

解决方法

我正在尝试从Spring Boot Rest服务下载文件。

@requestMapping(path="/downloadFile",method=requestMethod.GET)
    @Consumes(MediaType.APPLICATION_JSON_value)
    public  ResponseEntity<InputStreamReader> downloadDocument(
                String acquistionId,String fileType,Integer expressvfId) throws IOException {
        File file2Upload = new File("C:\\Users\\admin\\Desktop\\bkp\\1.rtf");
        httpHeaders headers = new httpHeaders();
        headers.add("Cache-Control","no-cache,no-store,must-revalidate");
        headers.add("Pragma","no-cache");
        headers.add("Expires","0");
        InputStreamReader i = new InputStreamReader(new FileInputStream(file2Upload));
        System.out.println("The length of the file is : "+file2Upload.length());

        return ResponseEntity.ok().headers(headers).contentLength(file2Upload.length())
                .contentType(MediaType.parseMediaType("application/octet-stream"))
                .body(i);
        }

当我尝试从浏览器下载文件时,它开始下载,但始终失败。服务有什么问题导致下载失败?

大佬总结

以上是大佬教程为你收集整理的从Spring Boot Rest服务下载文件全部内容,希望文章能够帮你解决从Spring Boot Rest服务下载文件所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。