vue3+springboot+element-plus生成附件上传并浏览功能
时间: 2023-07-27 09:05:56 浏览: 525
vue+springboot图片上传和显示的示例代码
5星 · 资源好评率100%
要实现Vue3和Spring Boot框架下的Element Plus附件上传和浏览功能,可以按照以下步骤进行操作:
1. 前端实现
在Vue3项目中,可以使用Element Plus提供的el-upload组件进行上传,同时利用axios发送上传请求,具体实现可以参考上一篇回答的代码示例。
在附件浏览的功能中,可以使用Element Plus提供的el-dialog组件和el-table组件,具体实现可以参考以下代码示例:
```vue
<template>
<div>
<el-upload
class="upload-demo"
action="/api/upload"
:on-success="handleSuccess"
:file-list="fileList"
multiple
:limit="3"
:on-exceed="handleExceed"
:headers="headers">
<el-button size="small" type="primary">点击上传</el-button>
<div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div>
</el-upload>
<el-button type="primary" @click="showDialog">查看附件</el-button>
<el-dialog title="附件列表" :visible.sync="dialogVisible" width="50%">
<el-table :data="fileTableData" border>
<el-table-column prop="filename" label="文件名"></el-table-column>
<el-table-column prop="size" label="文件大小"></el-table-column>
<el-table-column label="操作">
<template v-slot="scope">
<a :href="'/api/download/' + scope.row.filename">下载</a>
</template>
</el-table-column>
</el-table>
</el-dialog>
</div>
</template>
<script>
import axios from 'axios'
export default {
data() {
return {
fileList: [],
headers: {
Authorization: 'Bearer ' + localStorage.getItem('token'),
},
dialogVisible: false,
fileTableData: [],
}
},
methods: {
handleSuccess(response, file, fileList) {
this.$message.success('上传成功')
this.fileList = fileList
},
handleExceed(files, fileList) {
this.$message.warning(`当前限制选择 3 个文件,本次选择了 ${files.length} 个文件,共选择了 ${fileList.length + files.length} 个文件`)
},
showDialog() {
axios.get('/api/files')
.then(response => {
this.fileTableData = response.data
this.dialogVisible = true
})
.catch(error => {
console.log(error)
})
},
},
}
</script>
```
其中,`/api/files`接口可以用来获取已上传的附件列表,返回的数据格式可以是一个包含文件名和文件大小的对象数组,例如:
```json
[
{ "filename": "file1.txt", "size": "123KB" },
{ "filename": "file2.jpg", "size": "456KB" },
{ "filename": "file3.pdf", "size": "789KB" }
]
```
2. 后端实现
在Spring Boot项目中,可以使用Spring Boot提供的MultipartFile类来处理上传的附件,同时可以使用Spring Boot提供的ResponseEntity类来处理下载请求,具体实现可以参考以下代码示例:
```java
@RestController
@RequestMapping("/api")
public class FileController {
private static final String UPLOAD_FOLDER = "uploads/";
@PostMapping("/upload")
public ResponseEntity<?> uploadFile(@RequestParam("file") MultipartFile file) {
try {
String filename = file.getOriginalFilename();
String filepath = Paths.get(UPLOAD_FOLDER, filename).toString();
Files.write(Paths.get(filepath), file.getBytes());
return ResponseEntity.ok().build();
} catch (IOException e) {
e.printStackTrace();
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
}
@GetMapping("/files")
public ResponseEntity<List<FileMetadata>> getFiles() {
List<FileMetadata> files = new ArrayList<>();
File uploadFolder = new File(UPLOAD_FOLDER);
if (uploadFolder.exists()) {
File[] fileList = uploadFolder.listFiles();
if (fileList != null && fileList.length > 0) {
for (File file : fileList) {
FileMetadata metadata = new FileMetadata(file.getName(), humanReadableByteCount(file.length()));
files.add(metadata);
}
}
}
return ResponseEntity.ok(files);
}
@GetMapping("/download/{filename:.+}")
public ResponseEntity<Resource> downloadFile(@PathVariable String filename) {
Path filepath = Paths.get(UPLOAD_FOLDER, filename);
Resource resource;
try {
resource = new UrlResource(filepath.toUri());
} catch (MalformedURLException e) {
e.printStackTrace();
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
if (resource.exists() && resource.isReadable()) {
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + filename);
return ResponseEntity.ok().headers(headers).body(resource);
} else {
return ResponseEntity.notFound().build();
}
}
private static String humanReadableByteCount(long bytes) {
if (bytes < 1024) {
return bytes + "B";
}
int exp = (int) (Math.log(bytes) / Math.log(1024));
String pre = "KMGTPE".charAt(exp - 1) + "i";
return String.format("%.1f%sB", bytes / Math.pow(1024, exp), pre);
}
private static class FileMetadata {
private final String filename;
private final String size;
public FileMetadata(String filename, String size) {
this.filename = filename;
this.size = size;
}
public String getFilename() {
return filename;
}
public String getSize() {
return size;
}
}
}
```
其中,`/api/download/{filename}`接口可以用来处理下载请求,返回的是一个附件文件流,可以在前端实现中通过a标签的href属性来实现下载。
阅读全文