The front-end and back-end operations of uploading and receiving images in the SpringBoot project

1. Introduction to the problem

In an online image sharing system, the front end uses JS+jQuery, the back end uses Maven to manage the project, and a SSM (Spring+SpringBoot+Mybatis) project written in Java language adopts a hierarchical directory structure (Controller, Service, Mapper, etc.) , you need to implement a front-end tag to upload images, and the back-end Controller layer receives and processes the images.

2. Front-end image upload solution

1.Upload

There are many ways to upload images, which can be processed using base64, blob and other types. In this article, the front-end upload image uses the file type of the native JS tag input:

<input type="file">

After selecting a file with this tag, the path of the image will be displayed in this tag, but it is obviously not possible to obtain the image directly using this tag (you can only see the image by accessing the local path, but the web page does not understand what this path means. picture file).

2. The front-end web page displays the uploaded image

(1) HTML code:

<input type="file" id="uploadimage" accept="image/gif,image/jpeg,image/jpg,image/png,image/svg">
<img id="showimage" style="width: auto;height: 80%;" src="" alt="请上传图片">

Attribute explanation:
<input> tag:
id: ID attribute value, used for JS to locate the tag;
type: set to file, providing a button that can upload files;
accept: as the name suggests, it limits the types of files accepted, and stipulates this attribute The value can limit the file type to pictures, such as .jpg, .png (high definition), .gif (animation), .jpeg, .svg (not recommended); <img> tag: id: same as above;
style
:
style setting;
src: path;
alt: default text when loading the image fails or src is empty.

(2) JS code:

 document.getElementById("uploadimage").onchange = function(){
    
    //当input标签上传了一个图片时
     var file = this.files;//将当前图片文件赋值给file变量
     var reader = new FileReader();//创建一个新FileReader类
     reader.readAsDataURL(file[0]);//将图片文件传给该FileReder
     reader.onload = function ()//加载
     {
    
    
         var image = document.getElementById("showimage");
         image.src = reader.result;
     };
 }

3. Upload the image file on the front end

Use JS code to process the file, and use the FormData type to send the image to the backend in the form of a binary stream:
JS code:
Usage of the FormData class:

var formData = new FormData();
formData.set("file", document.getElementById('uploadimage').files[0]);

Use $.ajax to send the request:

$.ajax({
    
    
    url: "images/insertOneImageFile",//后端Controller层处理图片文件的对应接口
    type: "post",
    data: formData,//发送的数据为FormData类
    async: false,
    cache: false,
    processData: false,   // 不处理发送的数据
    contentType: false,   // 不设置Content-Type请求头
    success:function (data) {
    
    
        $("#path").text(data);
        console.log(data);
    },
    error: function(error){
    
    
        imagestring = "";
        alert("上传图片出错!");
    }
});

4. Backend processing FormData:

Controller layer code:

    @RequestMapping("/insertOneImageFile")
    public String insertOneImageFile(HttpServletRequest request, HttpServletRequest response, HttpSession session){
    
    
        MultipartHttpServletRequest multipartRequest=(MultipartHttpServletRequest) request;
        MultipartFile multipartFile = multipartRequest.getFile("file");
        assert multipartFile != null;
        MultipartFileToFile.saveMultipartFile(multipartFile, "src/main/resources/static/images");
        return MultipartFileToFile.saveMultipartFile(multipartFile, "target/classes/static/images");
    }

Tool class 1 used to save images to local paths : MultipartFileToFile.class:
(Note: This article has configured Spring and SpringBoot environments by default)

package com.id.utils;

import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.UUID;

/**
 * @Description 存储和删除MultipartFile文件
 * @Author haoyalei
 **/
public class MultipartFileToFile {
    
    

    /**
     *
     * @param file
     * @param targetDirPath 存储MultipartFile文件的目标文件夹
     * @return 文件的存储的绝对路径
     */
    public static String saveMultipartFile(MultipartFile file, String targetDirPath){
    
    

        File toFile = null;
        if (file.equals("") || file.getSize() <= 0) {
    
    
            return null;
        } else {
    
    

            /*获取文件原名称*/
            String originalFilename = file.getOriginalFilename();
            /*获取文件格式*/
            String fileFormat = originalFilename.substring(originalFilename.lastIndexOf("."));

            String uuid = UUID.randomUUID().toString().trim().replaceAll("-", "");
            toFile = new File(targetDirPath + File.separator + uuid + fileFormat);

            String absolutePath = null;
            try {
    
    
                absolutePath = toFile.getCanonicalPath();

                /*判断路径中的文件夹是否存在,如果不存在,先创建文件夹*/
                String dirPath = absolutePath.substring(0, absolutePath.lastIndexOf(File.separator));
                File dir = new File(dirPath);
                if (!dir.exists()) {
    
    
                    dir.mkdirs();
                }

                InputStream ins = file.getInputStream();

                inputStreamToFile(ins, toFile);
                ins.close();

            } catch (IOException e) {
    
    
                e.printStackTrace();
            }



            return uuid + fileFormat;//uuid为保存时所使用的文件名;fileFormat为文件扩展名(.jsp什么的)
        }

    }

    //获取流文件
    private static void inputStreamToFile(InputStream ins, File file) {
    
    
        try {
    
    
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
    
    
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
    
    
            e.printStackTrace();
        }
    }

    /**
     * 删除本地临时文件
     *
     * @param file
     */
    public static void deleteTempFile(File file) {
    
    
        if (file != null) {
    
    
            File del = new File(file.toURI());
            del.delete();
        }
    }
}

postscript

Since this topic selection procedure is not easy to make public, only the core code is posted here.


  1. Reference link: https://blog.csdn.net/weixin_45379185/article/details/125852990 ↩︎

Guess you like

Origin blog.csdn.net/weixin_47278656/article/details/129976147