SpringBoot 上传图片-指定目录按照日期存储

该文章介绍了一个SpringBoot应用中如何实现图片上传并按照日期存储到指定目录,利用YAML配置文件设定文件保存路径,通过WebMvcConfigurer配置静态资源处理,确保上传后的图片可以被正确访问。
摘要由CSDN通过智能技术生成

SpringBoot 上传图片-指定目录按照日期存储

1. 在配置文件中指定文件保存根目录

我用的yaml,用properties也行

file-save-path: D:/upload/

2. 文件上传接口

package com.admin.controller.wechat;

import cn.hutool.core.lang.UUID;
import com.redic.base.Result;
import com.redic.utils.UploadImg;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

@RestController
@RequestMapping("/weChat/img")
public class ImgController {
    /**
     * 时间格式化
     */
    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd/");

    /**
     * 图片保存路径,自动从yml文件中获取数据
     *   示例
     */
    @Value("${file-save-path}")
    private String fileSavePath;
    @Value("${server.servlet.context-path}")
    private String contextPath;


    @PostMapping("/uploadImage")
    public Result uploadImg(MultipartFile file, HttpServletRequest request) {
        //1.后半段目录: 
        String directory = simpleDateFormat.format(new Date());
        /**
         *  2.文件保存目录  
         *  如果目录不存在,则创建
         */
        File dir = new File(fileSavePath + directory);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        //3.给文件重新设置一个名字
        //后缀
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        String newFileName= UUID.randomUUID().toString().replaceAll("-", "")+suffix;
        //4.创建这个新文件
        File newFile = new File(fileSavePath + directory + newFileName);
        //5.复制操作
        try {
            file.transferTo(newFile);
            String url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() +contextPath+"/upload/" + directory + newFileName;
            return Result.success("图片上传成功",url);
        } catch (IOException e) {
            return Result.success("图片上传失败");
        }
    }

}

3. 新增配置类对静态资源处理

addResourceHandlers中对请求路径为/upload/**的请求替换为"file:"+fileSavePath

例如:

请求127.0.0.1/upload/1.png就会修改为file:D:/upload/1.png

package com.admin.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @author zr
 * @date 2023/5/23 9:28
 */
@Configuration
public class WebConfig implements WebMvcConfigurer {
    /**
     * 图片保存路径,自动从yml文件中获取数据
     */
    @Value("${file-save-path}")
    private String fileSavePath;

    /**
     * 静态资源处理
     **/
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry
                .addResourceHandler("/upload/**")
                .addResourceLocations("file:"+fileSavePath);
    }
}

4. 上传测试

image-20230527175752575

此时将我们上传的文件存放在我们配置的根目录及对应日期目录下

image-20230527175815283

5. 访问测试

成功!

image-20230527175853759

6. 注意事项

image-20230527180210084

7. 上传接口返回url报404排查

最简单的方法就是点击下图所指的位置

image-20230527180317162

浏览器的打开的路径才是项目的根路径,不然返回的url会404找不到

image-20230527180411859

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值