LuoliangDSGA’s blog blog address: Luoliangdsga.github. IO welcome to reprint, reprint please indicate the author and source, thank you!

SpringBoot+ vue. js implements file uploading separated from the front and back ends

This article needs some knowledge of Vue and SpringBoot, divided into two projects, one is the front-end Vue project, one is the back-end SpringBoot project.

Back-end project setup

Create a new SpringBoot project using IDEA and press Next

After a successful project is created, Maven’s 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>
Copy the code

Next, write the API interface for uploading

@RestController
@RequestMapping("/upload")
@CrossOrigin
public 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("File parameters passed in: {}", JSON.toJSONString(file, true));
        if (Objects.isNull(file) || file.isEmpty()) {
            logger.error("File is empty");
            return "File is empty. Please upload it again.";
        }

        try {
            byte[] bytes = file.getBytes();
            Path path = Paths.get(UPLOAD_FOLDER + file.getOriginalFilename());
            // If there is no files folder, create it
            if(! Files.isWritable(path)) { Files.createDirectories(Paths.get(UPLOAD_FOLDER)); }// Write the file to the specified path
            Files.write(path, bytes);
            logger.debug("File write success...");
            return "File uploaded successfully";
        } catch (IOException e) {
            e.printStackTrace();
            return "Backend exception..."; }}}Copy the code
  • CrossOrigin annotations: Solve cross-domain problems, because the front and back end are completely separated, cross-domain problems are always possible, adding this annotation will make the Controller cross-domain support, if removed, front-end Ajax requests will not go to the back end. This is just one cross-domain solution, and there are other solutions that are not covered in this article.
  • MultipartFile: The SpringMVC MultipartFile object that receives FormData incoming from the front-end request.
  • PostMapping PostMapping is a new annotation introduced after Spring4.3 to simplify the mapping of HTTP methods. It is equivalent to @requestmapping (value = “/xx”, method = requestmethod.post).

The back end is done at this point, very simple.

Front-end project setup

I used Node8+Webpack3+Vue2

The Node environment needs to be installed locally, and vuE-CLI is installed. Use VUe-CLI to generate a Vue project.

After the project is successfully created, open it with WebStorm and write a simple upload example. The main code is as follows:

<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
    <form>
      <input type="file" @change="getFile($event)">
      <button class="button button-primary button-pill button-small" @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) {
        // Prevents the element 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>
Copy the code

Use Axios to send Ajax requests to the back end, and use H5’s FormData object to wrap image data

test

Start the server and run the main method of the BootApplication class directly on port 8082

Start the front-end, port 8080 by default, CD to the front-end directory, respectively:

  • npm install
  • npm run dev

After successful startup, access localhost:8080

Select an image to upload, you can see that after the upload is successful, there is also an image file in the specified directory on the backend

conclusion

This article is a simple demo, can only deal with small file upload, later I will write a SpringBoot+Vue implementation of large file block upload, please look forward to. Welcome star: boot-upload.