SpringBoot上传图片到指定目录并回显

一、概述

  案例:

    1.利用SpringBoot写一个后台

    2.接收前端传递过来的图片并保存到服务器。

    3.前端可以通过url访问上传过的图片

  步骤:

    1.写一个FileController专门用来接收前端提交的图片文件,并把图片保存到服务器的指定位置

    2.配置WebMvcCongurer,在其addResourceHandlers方法中设置资源映射

    3.编写前端进行测试

二、代码示例

    1.FileInfoController.java

@RequestMapping(value = "upload", method = RequestMethod.POST)
    public ResultOk upload(@RequestParam("file") MultipartFile file) {
       // 获取文件在服务器上的存储位置
        String serverPath = globalProperties.getFilePath();
        // 获取允许上传的文件扩展名
        String extension = globalProperties.getExtension();
        File filePath = new File(serverPath);
        log.info("文件保存的路径为:" + filePath);
        if (!filePath.exists() && !filePath.isDirectory()) {
            log.info("目录不存在,则创建目录:" + filePath);
            filePath.mkdir();
        }
        // 判断文件是否为空
        if (file == null) {
            return new ResultOk(200,"参数文件为空");
        }
        //判断文件是否为空文件
        if (file.getSize() <= 0) {
            return new ResultOk(200,"文件为空");
        }

        // 判断文件大小不能大于50M
        if (DEFAULT_MAX_SIZE != -1 && file.getSize() > DEFAULT_MAX_SIZE) {
            return new ResultOk(200,"文件不能大于50M");
        }

        // 获取文件名
        String fileName = file.getOriginalFilename();
        // 获取文件扩展名
        String fileExtension = fileName.substring(fileName.lastIndexOf(".")).toLowerCase();

        // 判断文件扩展名是否正确
        if (!extension.contains(fileExtension)) {
            return new ResultOk(200,"文件扩展名不正确");
        }

        FileInfo fileInfo = new FileInfo();
        // 重新生成的文件名
        String saveFileName = System.currentTimeMillis() + fileExtension;
        // 在指定目录下创建该文件
        File targetFile = new File(filePath, saveFileName);

        log.info("将文件保存到指定目录");
        try {
            file.transferTo(targetFile);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        // 保存数据
        fileInfo.setFileName(fileName);
     //要存入数据库的图片的全路径,其中images是访问图片的前缀(和WebMvcConfigurer中设置的资源映射关系保持一致) fileInfo.setFilePath(
"http://localhost:8081/images/" + saveFileName); fileInfo.setFileSize(file.getSize()); log.info("新增文件数据"); // 新增文件数据 return fileService.upload(fileInfo); }

  2.设置服务器图片资源映射关系

@Configuration
public class InterceptorConfig implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //图片资源映射
     //其中/images是访问图片资源的前缀,比如要访问test1.png。则全路径为:http://localhost:端口号/images/test1.png registry.addResourceHandler("/images/**") .addResourceLocations("file:E:/tony/demo/res/");//此处为设置服务端存储图片的路径(前段上传到后台的图片保存位置)
} }

  

  3.以上两步设置完成后就可以在在浏览器中访问上传到服务端的图片了,例如:http://localhost:8081/images/1698054658204.jpeg

 

posted on 2023-10-23 17:52  飘杨......  阅读(2604)  评论(0)    收藏  举报