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>

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

### 实现Vue3与SpringBoot集成以支持连续上传九宫格图片 #### 后端配置 (Spring Boot) 为了处理文件上传请求,在 Spring Boot 中需要设置 `MultipartConfig` 并创建相应的控制器来接收前端发送过来的数据。 ```java import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; @RestController @RequestMapping("/api/upload") public class ImageUploadController { @PostMapping("/images") public String handleFileUpload(@RequestParam("files") MultipartFile[] files) { for (MultipartFile file : files) { try { // 处理每个文件的保存逻辑... System.out.println(file.getOriginalFilename()); } catch (Exception e) { return "Error occurred while uploading."; } } return "Files uploaded successfully!"; } } ``` 此代码片段定义了一个 RESTful API 接口用于接受多张图片的同时上传[^1]。 #### 前端实现 (Vue 3) 在 Vue 组件内,通过 `<input type="file">` 来获取用户选择的照片,并利用 Axios 库向服务器发起 POST 请求完成实际传输操作。 ```html <template> <div> <!-- 使用v-for循环渲染已选中的缩略图 --> <ul v-if="selectedImages.length"> <li v-for="(image, index) in selectedImages" :key="index"> <img :src="image.previewUrl"/> </li> </ul> <!-- 文件输入框允许一次选择多个文件 --> <label>Choose Images:</label> <input type="file" multiple accept=".jpg,.jpeg,.png" @change="onImageSelect"/> <button @click="uploadImages()">Upload</button> </div> </template> <script setup lang="ts"> import { ref } from 'vue'; import axios from 'axios'; const selectedImages = ref([]); function onImageSelect(event: Event): void { const target = event.target as HTMLInputElement; if (!target.files || !Array.from(target.files).length) return; Array.from(target.files).forEach((file) => { let reader = new FileReader(); reader.onloadend = () => { selectedImages.value.push({ name: file.name, previewUrl: reader.result?.toString() ?? '' }); }; reader.readAsDataURL(file); }); } async function uploadImages(): Promise<void> { const formData = new FormData(); selectedImages.value.forEach(({name}, idx) => { formData.append('files', document.querySelector<HTMLInputElement>('input[type=file]').files[idx], name); }); await axios.post('/api/upload/images', formData, { headers: {'Content-Type': 'multipart/form-data'} }).then(response => console.log(response.data)).catch(error => alert(`Failed to Upload ${error}`)); } </script> ``` 这段代码展示了如何构建一个简单的界面让用户可以选择并展示最多9张照片作为预览,之后点击按钮触发批量上传至服务端的操作[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值