SpringBoot+Vue+token实现(表单+图片)上传、图片地址保存到数据库。上传图片保存位置到项目中的静态资源下、图片可以在前端回显(二))

完整的思路以及代码在第一篇中、这里进行部分优化。

SpringBoot+Vue+token实现(表单+图片)上传、图片地址保存到数据库。上传图片保存位置自己定义、图片可以在前端回显(一))

前言

上一篇是将图片存放到磁盘上的具体位置、这样是有一个弊端的。就是当项目运行在其它的电脑上、对应的图片数据却没有。这是很不友好的设计。这一篇实现将图片存放到项目中的静态资源下。这样不论项目运行在哪台电脑上、都可以访问到静态资源中的图片

1、修改图片的存放位置

1.1 修改存放路径

package com.zyz.bookshopmanage.controller;

import cn.hutool.core.io.FileUtil;
import com.zyz.bookshopmanage.config.response.Result;
import com.zyz.bookshopmanage.mapper.GoodsFileInfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;


/**
 * @author Lenovo
 * @version 1.0
 * @data 2022/10/11 21:32
 */
@RestController
public class GoodsfileInfoController {
    @Autowired
    GoodsFileInfoMapper gfMapper;

    /**
     * System.getProperty("user.dir") 获取当前的工作目录 虚拟路径
     * E:\workspace\服装库存管理springboot+vue\book-mall-management
     */
    private static final String BASE_PATH = System.getProperty("user.dir") + "/src/main/resources/static/file/";
    private static final String VIRTUAL_FILE_PATH = "http://localhost:8282/images/";

//    private static final String ABSOLUTE_FILE_PATH = "E:\\Lenovo\\Documents\\upload\\images\\";

    /**
     * 文件上传 绝对
     * @param file
     * @return
     */
    @RequestMapping(value = "/goodsInfo/upload",method = RequestMethod.POST)
    public Result upload(MultipartFile file, HttpServletRequest request) throws IOException {
        System.out.println(System.getProperty("user.dir"));
        String originName = file.getOriginalFilename();
        // 1、文件名加个时间戳
        String fileName = FileUtil.mainName(originName) + System.currentTimeMillis() + "." + FileUtil.extName(originName);
        System.out.println(fileName);

        // 2、文件存放到项目中的静态资源下
        String storageName = BASE_PATH + fileName;

        // 3. 文件上传
        FileUtil.writeBytes(file.getBytes(),storageName );
        String final_fileName =VIRTUAL_FILE_PATH + fileName;
        return Result.ok().data("fileName",final_fileName);


        /**
         * FileUtil.writeBytes(file.getBytes(), BASE_PATH + fileName);


        System.out.println(fileName);

        GoodsFileInfo goodsFileInfo = new GoodsFileInfo();
        goodsFileInfo.setOriginName(originName);
        goodsFileInfo.setFileName(fileName);
        int result = gfMapper.insert(goodsFileInfo);
        if(result > 0){
            Map<String, Object> map = new HashMap<>();
            map.put("file_name", fileName);
            List<GoodsFileInfo> baseGFile = gfMapper.selectByMap(map);
            if(baseGFile != null){
                return Result.ok().data("baseGFile",baseGFile);
            }else{
                return Result.error().data("errMessage","查询失败");
            }
        }else{
            return Result.error().data("errMessage","文件上传失败");
        }

         */
        


    }
}

1.2 资源映射修改

package com.zyz.bookshopmanage.config;

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

/**
 * @author Lenovo
 * @version 1.0
 * @data 2022/10/12 18:58
 */
@Configuration
public class UrlConfig implements WebMvcConfigurer {
    private static final String BASE_PATH = System.getProperty("user.dir") + "/src/main/resources/static/file/";

    /**
     *  * 资源映射路径
     *  * addResourceHandler:访问映射路径
     *  * addResourceLocations:资源绝对路径
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/images/**").addResourceLocations("file:"+BASE_PATH);

    }

}


1.3 如果有拦截器、要放行静态资源

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        List<String> excludePath = new ArrayList<>();
        //排除拦截,除了注册登录(此时还没token),其他都拦截
        excludePath.add("/user/register");
        excludePath.add("/user/login");
        excludePath.add("/images/**");
        excludePath.add("/static/**");


        registry.addInterceptor(tokenInterceptor)
                .addPathPatterns("/**")
                .excludePathPatterns(excludePath);
        WebMvcConfigurer.super.addInterceptors(registry);
    }

2、实现的效果

在这里插入图片描述
在这里插入图片描述

在这里插入图片描述

3、后语

学无止境、加油吧

猜你喜欢

转载自blog.csdn.net/weixin_43304253/article/details/127295287
今日推荐