springboot图片上传工具类

本文介绍了一个用于Java的文件上传工具类,包括获取存储路径、将文件上传到硬盘以及生成唯一文件名的功能。该工具使用了Spring框架和Apache Commons IO库。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com.wiscom.ism.webapi.ismUtil;

import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;
@Component
public class FileUploadUtil {

    //存储路径
    public String getPath(){
        File path = null;
        try {
            path = new File(ResourceUtils.getURL("classpath:").getPath());
            if (!path.exists()){
                path.mkdirs();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        String imagesPath = path.getAbsolutePath();
        return imagesPath;
    }
    //上传存到硬盘
    public boolean upLoadImage(String imagesPath,String pathImg,InputStream fileInputStream){
        File file = new File(imagesPath,"static/"+pathImg);
        try {
            if (fileInputStream != null){
                FileUtils.copyInputStreamToFile(fileInputStream, file);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
    //生成名字
    public String imageName(String image){
        String imageName =null;
        //生成uuid作为文件名称
        String uuid = UUID.randomUUID().toString().replaceAll("-","").substring(0,10);
        //后缀
        String imgType =image.substring(image.lastIndexOf(".")+1,image.length());
        if ("gif".equals(imgType) || "jpg".equals(imgType) || "png".equals(imgType)){
            imageName=uuid+"."+imgType;
        }
        return imageName;
    }
}

 

转载于:https://www.cnblogs.com/maocai2018/p/10117024.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值