【前后端的那些事】15min快速实现图片上传,预览功能(ElementPlus+Springboot)
前端使用Vue.js和Element Plus实现图片上传和预览:
<template>
<el-upload
action="http://localhost:8080/upload"
list-type="picture-card"
:on-preview="handlePreview"
:on-success="handleSuccess"
:file-list="fileList"
>
<i class="el-icon-plus"></i>
</el-upload>
<el-dialog :visible.sync="dialogVisible">
<img width="100%" :src="dialogImageUrl" alt="">
</el-dialog>
</template>
<script>
export default {
data() {
return {
fileList: [],
dialogImageUrl: '',
dialogVisible: false
};
},
methods: {
handlePreview(file) {
this.dialogImageUrl = file.url;
this.dialogVisible = true;
},
handleSuccess(response, file, fileList) {
file.url = `http://localhost:8080/download/${response.data}`;
}
}
};
</script>
后端使用Spring Boot和Spring Web实现文件的上传和下载:
import org.springframework.web.bind.annotation.*;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.ResponseEntity;
import org.springframework.web.multipart.MultipartFile;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
@RestController
public class FileUploadController {
private static final String UPLOAD_DIR = System.getProperty("user.home") + "/.upload/";
@PostMapping("/upload")
public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) {
try {
Path uploadDir = Paths.get(UPLOAD_DIR);
if (!Files.exists(uploadDir)) {
Files.createDirectories(uploadDir);
}
String filename = file.getOriginalFilename();
Path filePath = uploadDir.resolve(filename);
Files.copy(file.getInputStream(), filePath);
return ResponseEntity.ok("File uploaded successfully: " + filename);
} catch (Exception e) {
return ResponseEntity.unprocessableEntity().body("Failed to upload the file");
}
}
@GetMapping("/download/{filename:.+}")
public ResponseEntity<Resource> downloadFile(@PathVariable String filename) {
try {
Path filePath = Paths.get(UPLOAD_DIR + filename);
Resource resource = new UrlResource(filePath.toUri());
if (resource.exists() || resource.isReadable()) {
return ResponseEntity.ok().body(resource);
评论已关闭