SpringBoot实现本地图片上传到本地文件夹(根据年月日创建文件夹)并实现URL预览

1.yml配置

file:
  upload-path: F:/path/to/upload/directory/
  upload-url: /upload/

2.上传Controller

import com.books.mode.result.AjaxResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.text.SimpleDateFormat;
import java.util.Date;

@RequestMapping("/upload/upload")
@RestController
public class UploadController {
    @Value("${file.upload-path}")
    private String uploadPath;

    @Value("${file.upload-url}")
    private String uploadUrl;

    @PostMapping("/file")
    public AjaxResult uploadFile(@RequestParam("file") MultipartFile file) throws IOException {
        try {
            if (file.isEmpty()) {
                return new AjaxResult(400, "文件为空", false);
            }
            SimpleDateFormat yearFormat = new SimpleDateFormat("yyyy");
            String yearPath = yearFormat.format(new Date());
            SimpleDateFormat monthFormat = new SimpleDateFormat("MM");
            String monthPath = monthFormat.format(new Date());
            SimpleDateFormat dayFormat = new SimpleDateFormat("dd");
            String dayPath = dayFormat.format(new Date());
            String folderPath = yearPath + "/" + monthPath + "/" + dayPath;
            File directory = new File(uploadPath + folderPath);
            if (!directory.exists()) {
                directory.mkdirs();
            }
            String orgName = file.getOriginalFilename();
            String suffixName = orgName.substring(orgName.lastIndexOf("."));
            String fileName;
            if (orgName.contains(".")) {
                fileName = "测试图片_" + System.currentTimeMillis() + suffixName;
            } else {
                return new AjaxResult(400, "不是文件/图片/视频", false);
            }
            Path destination = Paths.get(uploadPath, folderPath, fileName);
            Files.copy(file.getInputStream(), destination, StandardCopyOption.REPLACE_EXISTING); // 保存文件
            String fileUrl = "http://192.168.176.13:9090" + uploadUrl + folderPath + "/" + fileName;
            return new AjaxResult(200, "上传成功", fileUrl, true);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new AjaxResult(500, "内部异常", false);
    }
}

3.配置WebMvcConfig:配置资源映射路径和访问路径

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 WebMvcConfig implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/upload/**")
                .addResourceLocations("file:F:/path/to/upload/directory/");
    }
}

4.测试上传:使用Apifox或者Postman,可获取URL(data),供前端页面使用
在这里插入图片描述
5.浏览器上拼接完整地址预览图片
在这里插入图片描述

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值