首先创建一个SpringBoot项目。

创建一个SpringBoot项目
创建成功后在静态志愿目录下会产生static template 目录

当我们的SpringBoot项目启动时会自动配置好静态资源访问,当我们的静态资源文件放在resources目录下的static,public,resources, /META-INF/resources目录下时就可以直接访问
在这里插入图片描述

现在我们将一张图片放在public目录下
在这里插入图片描述

启动项目

浏览器输入http://localhost:5050/img/11.jpg
在这里插入图片描述

端口号是自己设置的img是public目录下的文件夹

从上面可以看见访问是ok的

那么现在如何上传图片呢?

简单几行代码教你实现 不仅可以上传图片,所有文件都可以上传

上代码

创建Controller层

package ink.awz.volunteer.controller;

import ink.awz.volunteer.utils.JsonResult;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @version 1.0
 * @Author:杨杰
 * @Date:2022/5/10 19:14
 */
@RestController
@ResponseBody
@Slf4j
@Api(tags = "图片处理")
public class ImgController {
    @RequestMapping(value = "imgUpDown",method = {RequestMethod.POST})
    public String imgUpDown(@RequestParam("file") MultipartFile file) throws IOException {
        //获取文件名
        String fileName = file.getOriginalFilename();
        //获取文件后缀名。也可以在这里添加判断语句,规定特定格式的图片才能上传,否则拒绝保存。
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        //为了避免发生图片替换,这里使用了文件名重新生成
        fileName = UUID.randomUUID()+suffixName;

        String path = ResourceUtils.getURL("classpath:").getPath()+"public/img/";
        file.transferTo(new File(path+fileName));

        return "http://localhost:5050/img/"+fileName;
    }
}

悄悄告诉你,上面代码可直接复制可用。

没错 代码到此结束。

下面测试
在这里插入图片描述

发送

在这里插入图片描述

访问

http://localhost:5050/img/cc1548fa-92fe-44f4-b5f7-baca197dd5f6.jpg

在这里插入图片描述

成功

接下还可以上传pdf等文件
在这里插入图片描述

发送
在这里插入图片描述

访问

http://localhost:5050/img/826ce92c-72f1-4fdd-9fc1-0d78a515a3df.pdf

在这里插入图片描述

ok的 自此就简单的完成了

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐