Springboot 上传文件或头像(MultipartFile、transferTo)

2023-04-17编程技术109520

1. 在配置文件中指定外部环境, 注入到代码中

头像上传路径, 若不存在, 会根据该路径创建指定路径文件夹

upload:
  path: d:\\upload\headimgs

创建类 fileutils 并读取配置文件中的值

@component
@configurationproperties(prefix = "upload")
@data
public class fileutils {
    private string path;
    public file getpath() {
        // 构建上传文件的存放 "文件夹" 路径
        string filedirpath = new string(path);
        file filedir = new file(filedirpath);
        if (!filedir.exists()) {
            // 递归生成文件夹
            filedir.mkdirs();
        }
        return filedir;
    }
    public boolean del(string filename) {
        file file = new file(path + file.separator + filename);
        return file.delete();
    }
    public boolean del(string path, string filename) {
        return new file(path + file.separator + filename).delete();
    }
}

2. 设置上传文件的限制配置

spring:
  servlet:
    multipart:
      max-request-size: 10mb # 上传文件的最大值
      max-file-size: 5mb # 单个文件上传的最大值 

3. 设置外部路径映射到url

创建config类
注意: 映射路径时, 最后面一定要加 / (file.separator)

@configuration
public class webmvcconfig extends webmvcconfigurationsupport {
    @autowired
    private fileutils fileutils;
    @override
    public void addresourcehandlers(resourcehandlerregistry registry) {
        // 加入头像文件夹映射 可通过 localhost:7188/headimage/....   访问到指定位置的图片
        registry.addresourcehandler("/static/**").addresourcelocations("classpath:/static/"); // 默认头像
        registry.addresourcehandler("/headimage/**").addresourcelocations("file:"+fileutils.getpath().getpath()+ file.separator);
        super.addresourcehandlers(registry);
    }
}

注意:

  • 此时映射了两个路径
  • 外部环境的路径static目录下的路径(该路径用于存放一张默认图片随意一张, 作为默认头像 可命名为 default.jpg)

4. 用户实体类中 加入 image 字段

该字段默认值为 ‘static/default.jpg’ 即为用户的默认头像
作用: 存放图片的相对路径

5. controller层编写

@restcontroller
@requestmapping("operate/user")
public class usercontroller extends basecontroller<userservice> {
    @apioperation("修改(可以修改头像和邮箱)")
    @putmapping
    public r modify(multipartfile headimg, string email){
        return baseservice.modify(headimg, email);
    }
}

6. service层编写

public interface userservice extends iservice<user> {
    r modify(multipartfile headimg, string email);
}
@slf4j
@service
public class userserviceimpl extends serviceimpl<userdao, user> implements userservice {
    @autowired
    private fileutils fileutils;
    /**
     * 获取当前用户名
     *
     * @return
     */
    private string getcurrentusername() {
       // ...
        return username;
    }
    /**
     * 获取当前用户
     *
     * @return
     */
    public user getcurrentuser() {
       // ...
        return user;
    }
    @override
    public r modify(multipartfile headimg, string email) {
        // 校验图片格式
        if (!imagetyperight(headimg)) return r.fail("图片格式不正确");
        // 获取上传文件后的路径
        string path = uploadfile(headimg);
        user currentuser = getcurrentuser();
        // 删除之前的头像(如果是默认头像不删除)
        string image = currentuser.getimage();
        if (!image.equals("static/default.png")) {
            if (!fileutils.del(image.substring(path.indexof("/") + 1))) {
                log.info("修改头像时, 原来的头像删除失败");
            } else {
                log.info("修改头像时, 原来的头像删除成功");
            }
        }
        // 修改数据库中头像的路径信息 和 邮箱
        update(wrappers.<user>lambdaupdate()
                .set(user::getemail, email)
                .set(user::getimage, path)
                .eq(user::getusername, currentuser.getusername()));
        // 该路径为图片相对路径 可放在url中的服务后面 进行访问
        // 比如: http://localhost:9000/cloudos-opt/headimage/01c8806dc26d45539b53c22c766cd250.jpg
        // http://localhost:9000/cloudos-opt/static/default.png
        return r.success(null, path);
    }
    /**
     * 验证图片的格式
     *
     * @param file 图片
     * @return
     */
    private boolean imagetyperight(multipartfile file) {
        // 首先校验图片格式
        list<string> imagetype = lists.newarraylist("jpg", "jpeg", "png", "bmp", "gif");
        // 获取文件名,带后缀
        string originalfilename = file.getoriginalfilename();
        // 获取文件的后缀格式
        string filesuffix = originalfilename.substring(originalfilename.lastindexof(".") + 1).tolowercase();  //不带 .
        if (!imagetype.contains(filesuffix)) return false;
        return true;
    }
     /**
     * 上传文件
     *
     * @param file
     * @return 返回路径
     */
    public string uploadfile(multipartfile file) {
        string originalfilename = file.getoriginalfilename();
        string filesuffix = originalfilename.substring(originalfilename.lastindexof(".") + 1).tolowercase();
        // 只有当满足图片格式时才进来,重新赋图片名,防止出现名称重复的情况
        string newfilename = uuid.randomuuid().tostring().replaceall("-", "") + "." + filesuffix;
        // 该方法返回的为当前项目的工作目录,即在哪个地方启动的java线程
        file filetransfer = new file(fileutils.getpath(), newfilename);
        try {
            file.transferto(filetransfer);
            log.info("头像上传: " + filetransfer.getpath());
        } catch (ioexception e) {
            e.printstacktrace();
        }
        // 将图片相对路径返回给前端
        return "headimage/" + newfilename;
    }
} 

7. 测试

获取默认头像的路径url为
http://localhost:8080/{spring-application-name}/static/default.jpg

修改头像
修改完成后, 返回相对路径

访问修改后的头像
带上相对路径在url上直接可以访问

 到此这篇关于springboot 上传文件或头像(multipartfile、transferto)的文章就介绍到这了,更多相关springboot 上传文件或头像内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

本文地址:https://www.ufcn.cn/tutorials/2512442.html

如非特殊说明,本站内容均来自于网友自主分享,概不代表本站观点,如有任何问题我们都将在收到反馈后的第一时间进行处理!