文件上传和回显
图
对于大型项目而言,有专门的文件管理系统,而针对小型项目,也可以直接对上传的文件做本地保存和回显,如果有使用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);
}