简易的springboot上传头像(图片)代码片段

 /**
     * 上传头像
     *
     * @throws IOException
     * @throws IllegalStateException
     */
    public String upload(MultipartFile file) throws IllegalStateException, IOException {

        File dir = new File(rootpath);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        //读取文件名
        String fileName = file.getOriginalFilename();
        if (!StringUtil.isEmpty(fileName)) {

            //获取文件的后缀
            String suffix = FilenameUtils.getExtension(fileName);
            //UUID.randomUUID().toString()是javaJDK提供的一个自动生成主键的方法,生成唯一的标识
            //修改后的文件名(带后缀)
            String newFileName = UUID.randomUUID().toString().toLowerCase() + "." + suffix;
            //public File(File parent, String child)--->dir就是相当于这个文件的路径(不包含这个文件的文件名),newFileName指的是文件名;
            File targetFile = new File(dir, newFileName);
            //将文件提交到目的地文件系统中
            file.transferTo(targetFile);

            System.out.println(newFileName + "mmm");
            //图片上传以后,“\\”要变成“/”、而且前面的根路径也不需要了;
            String imgpath = targetFile.getPath().replace("\\", "/").replace(rootpath, "");
            System.out.println(imgpath);
            return imgpath;
        } else {
            return null;
        }

    }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小鹿的周先生

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值