el-upload 获取文件 后端MultipartFile接收
时间: 2025-04-18 22:48:56 浏览: 29
### 使用 `el-upload` 组件上传文件并由后端通过 `MultipartFile` 接收
#### 前端配置 (`Vue.js`)
在前端部分,使用 Element Plus 提供的 `el-upload` 组件来处理文件的选择与提交。此组件允许自定义上传行为以及设置诸如最大文件数量等选项。
```html
<template>
<div>
<!-- 配置 el-upload -->
<el-upload
ref="upload"
:action="uploadUrl"
:headers="headers"
:on-success="handleSuccess"
:before-upload="beforeUpload"
:data="extraData"
multiple
:limit="3">
<el-button type="primary">点击上传</el-button>
</el-upload>
</div>
</template>
<script setup lang="ts">
import { ref } from 'vue';
const uploadUrl = '/api/upload'; // 设置上传的目标URL
const headers = {}; // 可选:如果需要携带认证信息或其他头部信息
const extraData = {
imgType: "jpg",
name: "上传测试",
imgSize: "12kb"
}; // 自定义表单字段传递给服务器
// 处理成功回调函数
function handleSuccess(response, file, fileList){
console.log('上传成功:', response);
}
// 文件上传前校验
function beforeUpload(file){
const isJPGOrPNG = file.type === 'image/jpeg' || file.type === 'image/png';
if (!isJPGOrPNG) {
ElMessage.error('仅支持 JPG 或 PNG 图片!');
}
return isJPGOrPNG;
}
</script>
```
上述代码片段展示了如何创建一个简单的文件上传界面,并指定了几个重要的属性:
- **`:action`**: 定义了请求发送的目的地 URL。
- **`:headers`**: 如果有身份验证需求,则可以在此处指定 HTTP 请求头。
- **`:data`**: 将额外的数据作为 POST 参数一起发送至服务端[^3]。
#### 后端 Java 实现 (Spring Boot)
对于 Spring Boot 应用程序而言,在控制器层面上可以通过如下方式接收来自客户端的文件流:
```java
@RestController
public class FileUploadController {
@PostMapping("/upload")
public ResponseEntity<String> uploadExhibitImg(@RequestParam("files") MultipartFile[] files,
HttpServletRequest request) throws IOException {
String result = "";
for(MultipartFile file : files){
try{
byte[] bytes = file.getBytes();
Path path = Paths.get(UPLOADED_FOLDER + file.getOriginalFilename());
Files.write(path, bytes);
result += "File uploaded successfully: " + file.getOriginalFilename() + "\n";
}catch(Exception e){
return new ResponseEntity<>(e.getMessage(), HttpStatus.EXPECTATION_FAILED);
}
}
return new ResponseEntity<>(result, HttpStatus.OK);
}
private static final String UPLOADED_FOLDER = "./uploads/";
}
```
这段代码实现了对多个文件的同时接收,并将它们保存到了本地磁盘上。需要注意的是,实际应用中应当更加严谨地对待路径管理和安全性考虑[^1]。
此外,当涉及到大型媒体文件比如 MP4 视频时,可能还需要采用更复杂的策略如分片上传以提高效率和支持断点续传等功能[^2]。
阅读全文
相关推荐


















