Spring web 文件上传

上传到服务器,这里讲tomcat


image.png
    @PostMapping("/saveImg.do")
    @ResponseBody
    public String saveImg(@RequestParam(value = "file", required = false) MultipartFile[] files,
                                  HttpServletRequest request) {
        //path 图片的保存路径  就是存到项目的根目录
        String path = (new File(request.getServletContext().getRealPath("/"))).getParent() + "/upload" + request.getContextPath() + "/image";
        // 调用上传方法
        List list = this.getUploadFile(files, path);
       // 将文件的保存路径存入数据库
        StringBuilder sb = new StringBuilder();
        if (!list.isEmpty()) {
            //存数据库
            for (String s : list) {
                sb.append("upload" + request.getContextPath() + "/image/" + String.valueOf(s) + ",");
            }
        }
        return sb.toString();
    }

着重讲解下文件的保存路径

image.png

接下来是文件上传的方法

public List getUploadFile(MultipartFile[] file, String savepath) {
        //获取多个文件的名称集合
        List files = new LinkedList();
        try {
            for (MultipartFile multipartFile : file) {
                 //文件原始命名
                String originName= multipartFile.getOriginalFilename();
                System.out.println("originName" + originName);
                // 文件重新命名
                String fileName =  System.currentTimeMillis() + originName;
                File targetFile = new File(savepath, fileName);
                if (!targetFile.exists()) {
                    targetFile.mkdirs();
                }
                // 保存
                try {
                    multipartFile.transferTo(targetFile);
                    files.add(fileName);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {

        }
        return files;
    }

将web项目部署在tomcat,进行测试

image.png

image.png

可以看到已经存进数据库,现在我们需要拿出来,需要做到的效果是,可以直接访问


image.png

image.png

取数据库字段拼url

   @Override
    public ServerResponse getImg(Integer fid, HttpServletResponse response) {
        //url 是tomcat项目路径
        String url = MyUtil.getTomcatUrl();
        //通过查询 查存图片的字段
        String img = workOrderMapper.selectImg(fid);
        List imgList = new ArrayList<>();
       //根据逗号分割
        if (!Transform.TestIsEmpty(img)) {
            String[] imgs = img.split(",");
            for (int i = 0; i < imgs.length; i++) {
                imgList.add(url + imgs[i]);
            }
        }
        return ServerResponse.createBySuccess(imgList);
    }

调用了工具类 拿到tomcat的url

package com.asset.util;

import com.asset.service.finance.FinPayService;
import com.asset.vo.request.FinPayManageReqVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.mvc.condition.RequestConditionHolder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


public class MyUtil {
    //获取后台项目路径
    public static String getUrl(){
        HttpServletRequest request=((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String path = request.getContextPath();
        String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
        return basePath;
    }

    //获取前端路径
    public static String getFrontUrl(){
        HttpServletRequest request=((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String path = request.getContextPath();
        String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort();
        return basePath;
    }

    //获取tomcat项目路径
    public static String getTomcatUrl() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

        String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/";
        return basePath;
    }
}

正常来讲文件上传应该是放在项目文件夹下,不过我是war打包上传的,每次重新上传war,会把原来的项目文件夹删除了再重新生成。

解决方式:

  • 将上传文件或图片存放在本地磁盘
  • 在本地磁盘创建一个文件管理的文件夹
  • 配置虚拟目录

详见
https://blog.csdn.net/qq_43072399/article/details/102397314

决定测试一下看效果

  1. 本地新建一个文件夹存放上传文件
  2. tomcat 配置虚拟路径

配置虚拟路径后需要重启服务器

tomcat --->conf---server.xml


image.png

image.png
image.png

你可能感兴趣的:(Spring web 文件上传)