Spring Boot 2.5.1 照片上传和查看

一、多张图片上传和查询

package com.example.demo.controller;

import com.example.demo.contrac.ErrorCode;
import com.example.demo.contrac.ResultBeanMsg;
import com.example.demo.entity.ResultBean;
import com.example.demo.entity.UpFileBean;
import com.example.demo.entity.User;
import com.example.demo.utils.GetErrorReturnBean;
import com.example.demo.utils.GetSucReturnBean;
import com.example.demo.utils.JdbcUtil;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.UUID;

@RestController
public class FileController {

    @GetMapping(value = "/file")
    public String file() {
        return "file";
    }


    @PostMapping(value = "/multFileUpload")
    public Object multFileUpload(@RequestParam(value = "file") MultipartFile[] fileArray, Model model, String userId) {
        if (fileArray.length == 0) {

            return GetErrorReturnBean.getErrrorBean(ErrorCode.CODE_405);
        }

        ArrayList stringPathList = new ArrayList<>();
        boolean isFlag = false;
        try {

            for (int i = 0; i < fileArray.length; i++) {
                MultipartFile file = fileArray[i];
                if(file.isEmpty()){
                    continue;
                }
                String fileName = file.getOriginalFilename();  // 文件名
                String suffixName = fileName.substring(fileName.lastIndexOf("."));  // 后缀名
                String filePath = "C://temp-rainy//"; // 上传后的路径
                fileName = UUID.randomUUID() + suffixName; // 新文件名
                File dest = new File(filePath + fileName);
                if (!dest.getParentFile().exists()) {
                    dest.getParentFile().mkdirs();
                }
                try {
                    file.transferTo(dest);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                String filenameUrl = "/upload-rainy/" + fileName;
                model.addAttribute("filename", filenameUrl);
                stringPathList.add(new UpFileBean("/image/"+fileName, fileName));
            }

        } catch (Exception e) {
            e.fillInStackTrace();
            System.out.println(e.getMessage());
            return GetErrorReturnBean.getErrrorBean(ErrorCode.CODE_402);
        }

        try {
            StringBuffer stringBuffer = new StringBuffer();
            for (int j = 0; j < stringPathList.size(); j++) {
                stringBuffer.append(stringPathList.get(j).getPath());
                if (stringPathList.size() - 1 != j) {
                    stringBuffer.append(",");
                }

            }

            Connection connection;
            Statement statement;
            try {
                //获取链接
                connection = JdbcUtil.getConnection();
                //获取sql执行对象
                statement = connection.createStatement();
            } catch (Exception e) {
                e.fillInStackTrace();
                return GetErrorReturnBean.getErrrorBean(ErrorCode.CODE_401);
            }


            //5.用执行SQL的对象去执行SQL(可能存在结果,需要查看返回结果)
            if (statement == null) {
                return GetErrorReturnBean.getErrrorBean(ErrorCode.CODE_403);
            }

            String sql = "UPDATE t_user SET userPhoto ='" + stringBuffer + "'WHERE userId = '" + userId + "'";

            long l = statement.executeLargeUpdate(sql);
            if (l != -1) {
                isFlag = true;
            }
        } catch (Exception e) {
            e.fillInStackTrace();
        }

        if (isFlag) {
            ResultBean resultBean = new ResultBean();
            resultBean.setList(stringPathList);
            resultBean.setCount(stringPathList.size());
            return GetSucReturnBean.sucReturnBean(resultBean, ResultBeanMsg.SUCCESS_UP_MSG);
        } else {
            ResultBean resultBean = new ResultBean();
            resultBean.setList(stringPathList);
            resultBean.setCount(stringPathList.size());
            return GetErrorReturnBean.getErrrorBean(ErrorCode.CODE_405);
        }

    }

    @PostMapping("getPhotoByUserId")
    public Object getPhotoByUserId(@RequestBody String userId) {
        try {
            JsonParser parser = new JsonParser();

            JsonObject asJsonObject = parser.parse(userId).getAsJsonObject();
            if (!asJsonObject.has("userId") || asJsonObject.get("userId").getAsString().isEmpty()) {
                return GetErrorReturnBean.getErrrorBean(ErrorCode.CODE_401);
            }

            String name1 = asJsonObject.get("userId").getAsString();
            System.out.print("入参:" + userId + "\r\n");
            Connection connection;
            Statement statement;

            try {
                //获取链接
                connection = JdbcUtil.getConnection();
                //获取sql执行对象
                statement = connection.createStatement();
            } catch (Exception e) {
                e.fillInStackTrace();
                return GetErrorReturnBean.getErrrorBean(ErrorCode.CODE_405);
            }


            //5.用执行SQL的对象去执行SQL(可能存在结果,需要查看返回结果)
            if (statement == null) {
                return GetErrorReturnBean.getErrrorBean(ErrorCode.CODE_403);
            }

            String sql = "SELECT userPhoto FROM t_user where userId = '" + name1 + "'";
            ResultSet resultSet = statement.executeQuery(sql);//返回的结果集,其中封装了我们全部的查询出来的结果
            ArrayList userArrayList = new ArrayList<>();

            while (resultSet.next()) {
                String userPhoto = resultSet.getString("userPhoto");
                if (userPhoto != null && !userPhoto.isEmpty()) {
                    String[] split = userPhoto.split(",");
                    for (int i = 0; i < split.length; i++) {
                        userArrayList.add(new UpFileBean(split[i], ""));
                    }
                }

            }

            JdbcUtil.release(connection, statement, resultSet);

            if (userArrayList.size() == 0) {
                return GetErrorReturnBean.getErrrorBean(ErrorCode.CODE_402, "未查询到");
            } else {
                ResultBean resultBean = new ResultBean();
                resultBean.setList(userArrayList);
                resultBean.setCount(userArrayList.size());
                return GetSucReturnBean.sucReturnBean(resultBean);
            }


        } catch (Exception e) {
            e.fillInStackTrace();
            System.out.print(e.getMessage());
            return GetErrorReturnBean.getErrrorBean(ErrorCode.CODE_401);

        }

    }
}


二、文件映射

package com.example.demo.controller;

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 FileAppconfigurer implements WebMvcConfigurer {
    // 定制资源映射
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //url 中读取到image时 会自定解析到file:C:/temp-rainy/
        //addResourceHandler image 对外 暴露的访问路径
        //addResourceLocations 文件指定的位置
        registry.addResourceHandler("/image/**").addResourceLocations("file:C:/temp-rainy/");
    }
}


三、验证

image.png

image.png

image.png
image.png

http://xxx.xx.110.131:8081/image/a91df70e-0f87-422a-b643-1087f1eb8363.jpg

你可能感兴趣的:(Spring Boot 2.5.1 照片上传和查看)