栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

springboot 图片上传

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

springboot 图片上传

文章目录

准备文件上传工具类

准备

    net.coobird
    thumbnailator
    0.4.14

文件上传工具类

说明:
文件上传到服务器时,按照日期来存放文件。
工具类名称 FileUtils.java

	
    public static Map fileUpload(MultipartFile file, String savePath) throws Exception{
        // 创建文件夹
        String path = FileUtil.createPath(savePath);

        BufferedOutputStream stream = null;
        byte[] bytes = file.getBytes();

        //获取文件名
        String fileName = file.getOriginalFilename().toLowerCase();

        //获取文件后缀名
        String  type = FileUtil.getFileTypeByPath(fileName);

        String uuidName = UUID.randomUUID().toString();
        fileName = uuidName + "." + type; // 新的文件名称uuid.type prefix

        String filePath = path + File.separator + fileName;
        File file1 = new File(filePath);//创建文件
        int i = 1;
        while (file1.exists()) {
            fileName = uuidName + "_" + i + "." + type;
            filePath = savePath + fileName;
            file1 = new File(filePath);
            i++;
        }

        stream = new BufferedOutputStream(new FileOutputStream(file1));
        stream.write(bytes);// 写入
        stream.close();

        //图片压缩
        Thumbnails.of(file1)
                .scale(1f)
                .outputQuality(0.25f)
                .outputFormat(type)
                .toFile(filePath);// 图片尺寸不变,压缩图片文件大小outputQuality实现,参数1为最高质量

        Map resMap = new HashMap();
        resMap.put("fileName",uuidName);
        resMap.put("fileType",type);
        resMap.put("filePath",filePath);
        resMap.put("dirPath",path);
        return resMap;
    }

	
    public static String createPath(String savePath){
        return createPath(savePath, null);
    }

    
    public static String createPath(String savePath,String format){
        // 以当前日期创建存放文件的文件夹,不存在文件夹则创建
        String setFormat = StringUtil.isEmpty(format)==true? "yyyyMMdd" : format ;
        String now = LocalDateTime.now().format(DateTimeFormatter.ofPattern(setFormat));
        File fileDir = new File(savePath + now);
        if (!fileDir.exists()) fileDir.mkdirs();
        return savePath + now;
    }

    
    public static String getFileTypeByPath(String path){
        //获取最后一个.的位置
        int lastIndexOf = path.lastIndexOf(".");
        //获取文件的后缀名 .jpg
        String type = path.substring(lastIndexOf + 1);
        return type;
    }

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/713049.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号