相关文章:
axios+springboot实现文件上传(文件以及表单)、下载(post/get方式)


简介

图片实际上就是图片下载功能

实现

①后端下载逻辑
就是接收前台传过来的文件名fileName,找到对应的文件返回给前台

@RequestMapping("/download")
public ResponseEntity<Object> downloadFile3(@RequestBody String fileName) {
    return downloadFile(fileName);
}

private ResponseEntity<Object> downloadFile(String fileName){
    String parentPath = getParentPath();
    File file = new File(parentPath, fileName);
    InputStreamResource resource = null;
    try {
        resource = new InputStreamResource(new FileInputStream(file));
    } catch (Exception e) {
        e.printStackTrace();
    }
    HttpHeaders headers = new HttpHeaders();
    headers.add("Content-Disposition", String.format("attachment;filename=\"%s", fileName));
    headers.add("Cache-Control", "no-cache,no-store,must-revalidate");
    headers.add("Pragma", "no-cache");
    headers.add("Expires", "0");
    ResponseEntity<Object> responseEntity = ResponseEntity.ok()
            .headers(headers)
            .contentLength(file.length())
            .contentType(MediaType.parseMediaType("application/octet-stream"))
            .body(resource);
    return responseEntity;
}

②前端代码:
因为是post请求,axios接收到的其实是二进制,这时候需要加上data:image/png;base64,前缀进行Base64编码,就可以正常显示了

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div id="uploadApp">

    <span>{{ saveFileName }}</span>
    <br/><br/><br/>
    <button @click="goPreview" style="width: 80px;height: 30px;">图片预览</button>

    <div id="imgShowModal" style="margin-left: 0;display: none;">
        <img :src="showImg">
    </div>

</div>

<script src="/js/public/jquery-3.4.1.min.js"></script>
<script src="/js/public/vue.min.js"></script>
<script src="/js/public/axios.min.js"></script>

<script>
    let app = new Vue({
        el: '#uploadApp',
        data: {
            bean: {},
            saveFileName: 'test.png',//要下载的文件名
            showImg: ''
        },
        methods: {
            goPreview: () => {
                axios({
                    method: "POST",
                    url: "/download",
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    data: app.saveFileName,
                    responseType: 'arraybuffer'//注意这里的类型
                }).then(response => {
                	//post接收到的字符串,这里要转换
                    return 'data:image/png;base64,' + btoa(new Uint8Array(response.data).reduce((data, byte) => data + String.fromCharCode(byte), ''));
                }).then(data => {
                    app.showImg = data;
                    $('#imgShowModal').show();
                });
            }
        }
    })
</script>
</body>
</html>

③效果展示:
在这里插入图片描述

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐