# Getting Started # spring boot 实现简单上传 1、pom.xml文件添加依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> 2、yml文件添加配置参数 server: port: 8080 servlet: context-path: /demo spring: servlet: multipart: enabled: true location: D:\ file-size-threshold: 5MB max-file-size: 20MB mvc: view: prefix: classpath:/templates/ suffix: .html static-path-pattern: /static/** 3. Add index.html in the templates directory. 4. MVC realizes page jump. Method 1. @Controller public class IndexController { @GetMapping("") public String index() { return "index"; } } Method 2. @RestController public class IndexController { @GetMapping("") public ModelAndView index() { ModelAndView modelAndView = new ModelAndView(); modelAndView.setViewName("index"); return modelAndView; } } RestController is equivalent to Controller + RequestBody, so in using RestController Need to configure the view parser 5, code to achieve file upload The specific code is as follows:
1. Upload function
@RestController @RequestMapping("upload") @Slf4j public class UploadController { @Value("${spring.servlet.multipart.location}") private String fileTempPath; @PostMapping(value = "/local", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) public Dict local(@RequestParam("file") MultipartFile file) { if (file.isEmpty()) { return Dict.create().set("code", 400).set("message", "文件内容为空"); } String fileName = file.getOriginalFilename(); String rawFileName = StrUtil.subBefore(fileName, ".", true); String fileType = StrUtil.subAfter(fileName, ".", true); String localFilePath = StrUtil.appendIfMissing(fileTempPath, "/") + rawFileName + "-" + DateUtil.current(false) + "." + fileType; try { file.transferTo(new File(localFilePath)); } catch (IOException e) { log.error("[File upload to local] failed, absolute path: {}", localFilePath); return Dict.create().set("code", 500).set("message", "File Upload failed"); } log.info("[File upload to local] absolute path: {}", localFilePath); return Dict.create().set("code", 200).set("message", " Uploaded successfully").set("data", Dict.create().set("fileName", fileName).set("filePath", localFilePath)); } }
2、index.html
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>spring-boot-demo-upload</title> <!-- import Vue.js --> <script src="https://cdn.bootcss.com/vue/2.5.17/vue.min.js"></script> <!-- import stylesheet --> <link href="https://cdn.bootcss.com/iview/3.1.4/styles/iview.css" rel="stylesheet"> <!-- import iView --> <script src="https://cdn.bootcss.com/iview/3.1.4/iview.min.js"></script> </head> <body> <div id="app"> <Row :gutter="16" style="background:#eee;padding:10%"> <i-col span="12"> <Card style="height: 300px"> <p slot="title"> <Icon type="ios-cloud-upload"></Icon> 本地上传 </p> <div style="text-align: center;"> <Upload :before-upload="handleLocalUpload" action="/demo/upload/local" ref="localUploadRef" :on-success="handleLocalSuccess" :on-error="handleLocalError" > <i-button icon="ios-cloud-upload-outline">选择文件</i-button> </Upload> <i-button type="primary" @click="localUpload" :loading="local.loadingStatus" :disabled="!local.file"> { { local.loadingStatus ? '本地文件上传中' : '本地上传' }} </i-button> </div> <div> <div v-if="local.log.status != 0">状态:{ {local.log.message}}</div> <div v-if="local.log.status === 200">File name: { {local.log.fileName}}</div> <div v-if="local.log.status === 200">File path: { {local.log.filePath}}</div> </div> </Card> </i-col> </ Row> </div> <script> new Vue({ el:'#app', data: { local: { // After selecting the file, save the file returned by beforeUpload here. File: null, / / Mark upload status loadingStatus: false, log: { status: 0, message: "", fileName: "", filePath: "" } }, yun: { // After selecting the file, save the file returned by beforeUpload here, file: null will be used later , // mark the upload status loadingStatus: false, log: { status: 0, message: "", fileName: "", filePath : "" } } }, methods: { // beforeUpload will stop automatic upload when it returns false or Promise. Here we save the selected file file in data and return false handleLocalUpload(file) { this.local. file = file; return false; }, // Here is a manual upload. The Upload instance is obtained through $refs, and then the private method .post() is called to upload the file saved in data. // When the Upload component of iView calls the .post() method, it will continue to upload. localUpload() { this.local.loadingStatus = true; // Mark the upload status this.$refs.localUploadRef.post(this.local.file); }, // After the upload is successful, clear the file in the data and modify the upload Status handleLocalSuccess(response) { this.local.file = null; this.local.loadingStatus = false; if (response.code === 200) { this.$Message.success(response.message); this.local.log .status = response.code; this.local.log.message = response.message; this.local.log.fileName = response.data.fileName; this.local.log.filePath = response.data.filePath; this.$refs.localUploadRef.clearFiles(); } else { this.$Message.error(response.message); this.local.log.status = response. code; this.local.log.message = response.message; } }, // After the upload fails, clear the file in data and modify the upload status handleLocalError() { this.local.file = null; this.local.loadingStatus = false; this.$Message.error('Upload failed'); }, // beforeUpload will stop automatic upload when it returns false or Promise. Here we save the selected file file in data and return false handleYunUpload(file) { this.yun.file = file; return false; }, // Here is manual upload, the Upload instance is obtained through $refs, and then the private method .post() is called to upload the file saved in data . // When the Upload component of iView calls the .post() method, it will continue to upload. yunUpload() { this.yun.loadingStatus = true; // Mark the upload status this.$refs.yunUploadRef.post(this.yun.file); }, // After the upload is successful, clear the file in the data and modify the upload Status handleYunSuccess(response) { this.yun.file = null; this.yun.loadingStatus = false; if (response.code === 200) { this.$Message.success(response.message); this.yun.log.status = response.code; this.yun.log.message = response.message; this.yun.log.fileName = response.data.fileName; this.yun.log.filePath = response.data.filePath; this.$refs.yunUploadRef.clearFiles(); } else { this.$Message.error(response.message); this.yun.log.status = response.code; this.yun.log.message = response.message; } }, // 上传失败后,清空 data 里的 file,并修改上传状态 handleYunError() { this.yun.file = null; this.yun.loadingStatus = false; this.$Message.error('上传失败'); } } }) </script> </body> </html>