This article requires a certain amount of knowledge about Vue and SpringBoot, and is divided into two projects, one is the front-end Vue project and the other is the back-end SpringBoot project.
Back-end project construction
I am using SpringBoot1.5.10+JDK8+IDEA Use IDEA to create a new SpringBoot project and click next
After the project is created successfully, the maven pom configuration is as follows
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <!--Add web module--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.39</version> </dependency> </dependencies>
Next, write the uploaded API interface
@RestController@RequestMapping("/upload")@CrossOriginpublic class UploadController { @Value("${prop.upload-folder}") private String UPLOAD_FOLDER; private Logger logger = LoggerFactory.getLogger(UploadController.class); @PostMapping("/singlefile") public Object singleFileUpload(MultipartFile file) { logger.debug("Incoming file parameters: {}", JSON.toJSONString(file, true)); if (Objects.isNull(file) || file.isEmpty()) { logger.error("File is empty"); return "File is empty, please upload again"; } try { byte[] bytes = file.getBytes(); Path path = Paths.get(UPLOAD_FOLDER + file.getOriginalFilename()); //If there is no files folder, create if (!Files.isWritable(path)) { Files.createDirectories(Paths.get(UPLOAD_FOLDER)); } //File writes to the specified path Files.write(path, bytes); logger.debug("File writes successfully..."); return "File uploads successfully"; } catch (IOException e) { e.printStackTrace(); return "Backend exception..."; } }} CrossOrigin annotation: Solve cross-domain problems, because the front and back ends are completely separated, cross-domain problems are inevitable. Adding this annotation will allow Controller to support cross-domain. If this annotation is removed, the front-end Ajax request will not reach the back-end. This is just a cross-domain solution, and there are other solutions. This article will not cover it for now.
MultipartFile: SpringMVC's multipartFile object, used to receive the FormData passed in by front-end requests.
PostMapping is a new annotation introduced after Spring 4.3. It is to simplify the mapping of HTTP methods, which is equivalent to the commonly used @RequestMapping(value = "/xx", method = RequestMethod.POST).
The backend has been completed so far, it is very simple.
Front-end project construction
I'm using Node8+Webpack3+Vue2
Locally, you need to install the node environment and install Vue-cli, and use Vue-cli to generate a Vue project.
After the project is successfully created, open it with WebStorm and you can write a simple upload example. The main code is as follows:
<template> <div> <h1>{{ msg }}</h1> <form> <input type="file" @change="getFile($event)"> <button @click="submit($event)"> Submit</button> </form> </div></template><script> import axios from 'axios'; export default { name: 'HelloWorld', data() { return { msg: 'Welcome to Your Vue.js App', file: '' } }, methods: { getFile: function (event) { this.file = event.target.files[0]; console.log(this.file); }, submit: function (event) { //Prevent elements from default behavior event.preventDefault(); let formData = new FormData(); formData.append("file", this.file); axios.post('http://localhost:8082/upload/singlefile', formData) .then(function (response) { alert(response.data); console.log(response); window.location.reload(); }) .catch(function (error) { alert("Upload failed"); console.log(error); window.location.reload(); }); } } } } }</script>Use Axios to send Ajax requests to the backend, encapsulate image data using H5's FormData object
test
Start the server and run the main method of the BootApplication class directly, port 8082
Start the front end, the port defaults to 8080, and cd to the front end directory, and execute them separately:
npm installnpm run dev
After successful startup, visit localhost:8080
Select an image to upload, you can see that after the upload is successful, there are also image files in the specified directory of the backend
Summarize
At this point, a separate upload demo with the front and back ends is completed. This article is a simple demo, which can only deal with the upload of small files. Later, I will write an article on SpringBoot+Vue to realize the upload of large files in chunks, so stay tuned. Attached with the source code, welcome to star: boot-upload.