一、文件上传
(1)后台代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
| package com.yyzy.controller;
import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import java.io.File; import java.io.IOException; import java.util.UUID;
@RestController public class FileUploadController {
public void deleteDirectory(File directory) { if (directory.isDirectory()) { for (File sub : directory.listFiles()) { deleteDirectory(sub); } } directory.delete(); }
@PostMapping("/upload") public String handleFileUpload(@RequestParam("file") MultipartFile file) { System.out.println("进入文件上传"); if (file.isEmpty()) { return "Please select a file to upload."; } try { byte[] bytes = file.getBytes(); String uploadDir = "D:\\项目单\\图书管理系统\\Library\\src\\main\\resources\\file\\"; File creatfile = new File(uploadDir);
if (!creatfile.exists()) { creatfile.mkdirs(); }
UUID uuid = UUID.randomUUID();
File uploadedFile = new File(uploadDir + uuid + ".png");
System.out.println(uploadedFile); file.transferTo(uploadedFile); System.out.println("成功文件上传"); return "File uploaded successfully!"; } catch (IOException e) { e.printStackTrace(); return "File upload failed!"; } } }
|
(2)前台代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
| <template> <div> <el-upload class="upload-demo" action="http://localhost:8081/upload" <!-- 上传文件的后端接口地址 --> :on-preview="handlePreview" :on-remove="handleRemove" :before-remove="beforeRemove" multiple :limit="3" :on-exceed="handleExceed" :file-list="fileList"> <el-button size="small" type="primary">点击上传</el-button> <div slot="tip" class="el-upload__tip">只能上传jpg/png 文件,且不超过 500kb</div> </el-upload> </div> </template>
<script> export default { data() { return { fileList: [ {name: 'food.jpeg', url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'}, {name: 'food2.jpeg', url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'} ] }; }, methods: { handleRemove(file, fileList) { console.log(file, fileList); }, handlePreview(file) { console.log(file); }, handleExceed(files, fileList) { this.$message.warning(`当前限制选择 3 个文件,本次选择了 ${files.length} 个文件,共选择了 ${files.length + fileList.length} 个文件`); }, beforeRemove(file, fileList) { return this.$confirm(`确定移除 ${ file.name }?`); } } } </script>
|
注意
前端代码中确实没有显式地传递 file
参数,但这是因为 el-upload
组件会自动处理文件上传的细节,包括将文件作为 multipart/form-data
请求的一部分发送到后端。
在 Element UI 的 el-upload
组件中,action
属性指定了上传文件的目标 URL,el-upload
组件会自动将选择的文件作为 multipart/form-data
请求的主体发送到指定的 URL。这个过程中,文件数据会被自动包含在请求中,并作为 file
参数传递给后端。
因此,尽管在前端代码中没有显式地看到传递 file
参数的代码,但实际上 el-upload
组件会处理这一切。您只需要确保 action
属性指向的后端接口地址是正确的,并且后端接口能够正确接收和处理这个文件参数。
以下是确保前端和后端正确配合的一些关键点:
- 前端
action
属性:确保 action
属性指向正确的后端接口地址,例如 http://localhost:8081/upload
。
- 后端接口参数:确保后端接口方法的参数使用
@RequestParam("file") MultipartFile file
接收文件数据。
1 2 3 4
| @PostMapping("/upload") public String handleFileUpload(@RequestParam("file") MultipartFile file) { }
|
- 文件类型和大小限制:虽然前端做了文件类型和大小的限制,但最好在后端也进行相应的验证,以确保安全性。
1 2 3
| if (file.isEmpty() || file.getSize() > 500 * 1024) { return "File is empty or exceeds the size limit."; }
|
- CORS 配置:如果您在本地开发环境中遇到跨域问题,请确保您的后端配置了 CORS(跨源资源共享)支持。
1 2 3 4 5
| @CrossOrigin(origins = "http://localhost:8080") @RestController public class FileUploadController { }
|
二、文件下载
(1)后端代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
| package com.yyzy.controller;
import org.springframework.core.io.Resource; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder;
import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; import java.util.stream.Collectors;
@Controller public class FileDownloadController {
private static final String FILE_DIRECTORY = "D:\\项目单\\图书管理系统\\Library\\src\\main\\resources\\file\\";
@GetMapping("/download/{fileName:.+}") @ResponseBody public ResponseEntity<Resource> downloadFile(@PathVariable String fileName) { Path filePath = Paths.get(FILE_DIRECTORY).resolve(fileName).normalize(); try { Resource resource = new org.springframework.core.io.UrlResource(filePath.toUri()); if (resource.exists() || resource.isReadable()) { return ResponseEntity.ok() .contentType(MediaType.APPLICATION_OCTET_STREAM) .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"") .body(resource); } else { return ResponseEntity.notFound().build(); } } catch (IOException ex) { ex.printStackTrace(); return ResponseEntity.status(500).build(); } } }
|