springboot + uniapp implements single file upload and image echoing

1. Use the uni-file-picker component tag

For specific usage, please see the introduction of uni-file-picker on the official website of uniapp.

Front-end code

The code is as follows. It is uploaded to the backend through uni.uoloadFile and returns url. The address is assigned value for image echo.

<template>
    <view class="container">
        <uni-file-picker file-mediatype="image" mode="grid" @select="select" />
        <!-- upload picture -->
        <image :src="value" mode=""></image>
    </view>
</template>

<script> export default {
        data() {
            return {
                value: ''
            }
        },
        methods: {
            select(e) {
                uni.uploadFile({
                    url: `http://localhost:5050/files/file`,//Your backend server address
                    filePath: e.tempFilePaths[0],//The path of the file resource to be uploaded
                    name: 'file',//The name corresponding to the file,The same as the attribute name received by the backend 
                    formData: {},//Other additional data in the request
                    success: (uploadFileRes) => {
                        this.value = uploadFileRes.data;
                    }
                });
            },
        }
    } </script>

<style lang="scss"> .container {
        width: 100%;
        height: 100%;
        background-color: #fff;
        position: fixed;
    } </style> 

Backend code

The first is the application.yml configuration file, the port number is configured as 5050, change it according to your needs.

The storage location of custom files: file:path: D://uploadPath/images/.

# The port number
server:
  port: 5050
spring:
  # File upload configuration
  servlet:
    multipart:      
      #Whether to enable file upload support,The default is true
      enabled: true
      #Threshold for writing files to disk,The default is0
      file-size-threshold: 0
      # Set the maximum size of a single file
      max-file-size: 10MB
      # Set the maximum requested size
      max-request-size: 100MB
# Custom image storage location
file:
  path: D://uploadPath/images/ 

controller control layer code

package com.test.blog.controller;

import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;

@RestController
@RequestMapping("/files")
public class FilesUnloadController {
    // File upload path
    @Value("${file.path}")
    private String filePath;

    // Single file upload
    @RequestMapping("/file")
    public String upload(@RequestParam MultipartFile file, HttpServletRequest request) {
        // Get server path
        String serverPath = request.getScheme() + "://" + request.getServerName()
                + ":" + request.getServerPort();
        // Get file name
        String fileName = file.getOriginalFilename();
        // save document
        File newFile = new File(filePath + '\\' + fileName);
        // Get fileurl
        String url = serverPath + "/images/" + fileName;
        // Determine whether the parent file directory exists,Create if it does not exist
        if (!newFile.getParentFile().exists()) {
            newFile.getParentFile().mkdirs();
            System.out.println("The parent file directory does not exist,Directory created");
        }
        try {
            // save document
            file.transferTo(newFile);
            System.out.println("File uploaded successfully");
        } catch (IOException e) {
            // program error
            e.printStackTrace();
            System.out.println("program error,Please re-upload");
        }
        // return file url
        return url;
    }
} 

Add a configuration class to map the static file mapping location, which can be accessed through url.

package com.test.blog.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class MyWebMvcConfig implements WebMvcConfigurer {
    // Set static resource mapping
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/images/**").addResourceLocations("file:D:/uploadPath/images/");
    }
} 

2. Use the uni.chooseImage interface

After obtaining the temporary file path of a local resource through the uni.chooseImage interface, you can upload the local resource to the specified server through this interface.

For specific usage, please see the introduction of uni.chooseImage on the official website of uniapp.

The back-end code is consistent with (1), and the front-end code is as follows:

<template>
    <view class="container">
        <!-- upload picture -->
        <image :src="value" mode=""></image>
        <button @click="uploadFile">upload picture</button>
    </view>
</template>

<script> export default {
        data() {
            return {
                value: ''
            }
        },
        methods: {
            uploadFile() {
                //Select a picture from your local photo album or take a photo with your camera。
                uni.chooseImage({
                    success: (chooseImageRes) => {
                        uni.uploadFile({
                            url: `http://localhost:5050/files/file`,//Your backend server address
                            filePath: chooseImageRes.tempFilePaths[0],//The path of the file resource to be uploaded
                            name: 'file',//The name corresponding to the file,The same as the attribute name received by the backend 
                            formData: {},//Other additional data in the request
                            success: (uploadFileRes) => {
                                this.value = uploadFileRes.data;
                            }
                        });
                    }
                });
            },  
        }
    } </script>

<style lang="scss"> .container {
        width: 100%;
        height: 100%;
        background-color: #fff;
        position: fixed;
    } </style>