axios+springboot实现图片预览(POST方式)

相关文章:
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>

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

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
这里提供一个简单的示例代码。 前端部分:使用Vue.js实现图片上传 1. 在Vue组件中定义一个文件上传input元素,并绑定一个change事件: ```html <template> <div> <input type="file" @change="handleFileUpload"> </div> </template> ``` 2. 在Vue组件中定义一个handleFileUpload方法,当文件上传input的值发生变化时,将上传的文件存储到data属性中的uploadedFile中: ```javascript <script> export default { data() { return { uploadedFile: null } }, methods: { handleFileUpload(event) { this.uploadedFile = event.target.files[0]; } } } </script> ``` 3. 在Vue组件中定义一个submit方法,将上传的文件发送到后端: ```javascript <script> export default { methods: { submit() { let formData = new FormData(); formData.append('file', this.uploadedFile); axios.post('/api/upload', formData, { headers: { 'Content-Type': 'multipart/form-data' } }) .then(response => { console.log(response.data); }) .catch(error => { console.log(error); }); } } } </script> ``` 后端部分:使用Spring Boot实现图片上传 1. 在Spring Boot中定义一个Controller,处理文件上传的请求: ```java @RestController @RequestMapping("/api") public class FileUploadController { @PostMapping("/upload") public String uploadFile(@RequestParam("file") MultipartFile file) { try { byte[] bytes = file.getBytes(); Path path = Paths.get("uploads/" + file.getOriginalFilename()); Files.write(path, bytes); return "File uploaded successfully!"; } catch (IOException e) { e.printStackTrace(); return "File upload failed!"; } } } ``` 2. 在Spring Boot的application.properties中配置文件上传的相关属性: ```properties spring.servlet.multipart.enabled=true spring.servlet.multipart.max-file-size=10MB spring.servlet.multipart.max-request-size=10MB ``` 注意:这里的配置表示上传的文件大小不能过10MB。 以上就是一个简单的vue+springboot上传图片的代码实现

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值