logo 范 · 拾光录
网址收集 关于作者 Github Gitee
杂文随笔4
Hexo博客:基础使用Hexo博客:Next主题Hexo博客:Next进阶使用Hexo博客:Next高级配置
前端编程3
前端基础知识16
UniApp15
Vue框架19
Java编程7
Java基础知识14
SpringBoot31
SpringMVC14
MyBatis8
SpringCloud15
RocketMQ1
MyCat1
数据库4
MySQL6
Redis7
MongoDB10
H21
Java技术栈4
知识整理分布式锁的实现方案MySQL事务MySQL的锁
软件工具箱14
IDEAGitMavenGradleNginx安装Nginx配置JMeter压测OllamaPicGoRustFSVSCodeDockerObsidianObs录制
Linux知识11
树莓派安装及使用ArchLinux:常用软件ArchLinux:基础系统安装ArchLinux:深度优化ArchLInux:图形化界面安装ArchLinux:Nirifrp内网穿透Jar启动脚本Linux常用命令VirtualBox安装CentOSVirtualBox安装Ubuntu
Python编程6
Python基础知识Python语法yolo目标检测OpenCV的使用及树莓派平台condauv
创意设计2
Blender:入门知识UI设计基础知识
AI相关9
Claude CodeHermes AgentOpenAI基本使用OpenAI工具调用OpenAI记忆管理OpenAI推理执行OpenAI开发框架Langchainllama.cpp

对于大型项目而言,有专门的文件管理系统,而针对小型项目,也可以直接对上传的文件做本地保存和回显,如果有使用Nginx,回显可以配置Nginx做,性能会更高

代码示例

import com.fan.model.Result;
import com.fan.service.CommonService;
import com.fan.utils.IdUtil;
import com.fan.utils.ProjectPath;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Objects;

/**
 * 图片
 */
@Slf4j
@Controller
public class ImageController {

    @Resource
    private CommonService commonService;

    /**
     * 图片上传
     */
    @RequestMapping("/manage/uploadImg")
    @ResponseBody
    public Result<String> uploadImg(@RequestParam("file") MultipartFile file) throws IOException {
        // 文件为空
        Assert.isTrue(!file.isEmpty(), "图片不能为空");
        // 文件格式限制
        Assert.isTrue(Objects.requireNonNull(file.getOriginalFilename()).contains("png") ||
                Objects.requireNonNull(file.getOriginalFilename()).contains("gif") ||
                Objects.requireNonNull(file.getOriginalFilename()).contains("jpg"), "仅支持png/jpg/gif图片");
        // 文件名
        String fileName = IdUtil.imageId();
        // 文件后缀
        String suffix = Objects.requireNonNull(file.getOriginalFilename()).substring(file.getOriginalFilename().lastIndexOf("."));
        // 文件路径
        String filePath = ProjectPath.getPath() + "/files/";
        File filePathReady = new File(filePath);
        if (!filePathReady.exists()) {
            boolean mkdirs = filePathReady.mkdirs();
            log.info("创建图片目录" + filePath + ":" + mkdirs);
        }
        File dest = new File(filePath + fileName + suffix);
        file.transferTo(dest);
        log.info("图片上传结果:成功");
        // 返回图片请求路径
        return Result.data("添加成功", "/image/" + fileName + suffix);
    }

    /**
     * 图片回显
     */
    @RequestMapping("/image/{id}")
    @ResponseBody
    public ResponseEntity<byte[]> show(@PathVariable String id) throws IOException {
        // 文件路径
        File dest = new File(ProjectPath.getPath() + "/files/" + id);
        // 返回图片类型
        byte[] data = new byte[(int) dest.length()];
        try (FileInputStream fileInputStream = new FileInputStream(dest)) {
            int read = fileInputStream.read(data);
        } catch (FileNotFoundException e) {
            // 文件不存在
            return new ResponseEntity<>(HttpStatus.NO_CONTENT);
        }
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.IMAGE_PNG);
        return new ResponseEntity<>(data, httpHeaders, HttpStatus.OK);
    }

}

路径工具

import org.springframework.boot.system.ApplicationHome;

import java.io.File;

/**
 * 获取项目绝对路径
 */
public class ProjectPath {

    /**
     * 获取程序执行目录,即Jar包所在的目录(开发环境为项目所在目录)
     */
    public static String getPath() {
        ApplicationHome applicationHome = new ApplicationHome(ProjectPath.class);
        File file = applicationHome.getSource();
        if (file == null) {
            return System.getProperty("user.dir");
        }
        return file.getParentFile().toString().replace("\\target", "");
    }

}

文件下载

/**
 * 文件下载
 */
@RequestMapping("/file/download/{name}")
@ResponseBody
public ResponseEntity<byte[]> show(@PathVariable String name) throws IOException {
    // 文件路径
    String filePath = ProjectPath.getPath() + "/files/" + name;
    // 文件路径
    File dest = new File(filePath);
    // 返回图片类型
    byte[] data = new byte[(int) dest.length()];
    try (FileInputStream fileInputStream = new FileInputStream(dest)) {
        int read = fileInputStream.read(data);
    } catch (FileNotFoundException e) {
        // 文件不存在
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }
    HttpHeaders httpHeaders = new HttpHeaders();
    // 名称
    httpHeaders.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + name);
    // 类型,指定名称后浏览器会自定判断类型
    httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
    return new ResponseEntity<>(data, httpHeaders, HttpStatus.OK);
}

MultipartFile转BufferedImage

MultipartFile img
BufferedImage image = ImageIO.read(img.getInputStream());
代码示例
路径工具
文件下载
MultipartFile转BufferedImage