文件上传方法

import com.sitech.cmap.process.engine.app.exception.BusinessException;
import com.sitech.cmap.process.engine.app.exception.ErrorCodeEnum;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;


public class test {
    public static Map<String, Object> upload(String uploadPath, MultipartFile file) {
        HashMap<String, Object> responseMap = new HashMap<>();

        if(file.getSize() > 1024 * 1024 * 5) {
            responseMap.put("code", 500);
            responseMap.put("msg", "文件过大,请上传5M以内的文件。");
            return responseMap;
        }
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
        if(!"png".equals(suffix) || !"jpg".equals(suffix)) {
            responseMap.put("code", 500);
            responseMap.put("msg", "文件格式不正确!只能上传.png/.jpg格式文件。");
            return responseMap;
        }

        /**
         * 存储空间 这里存储上传文件的文件夹按照年月日分类。
         */
        String BUCKET = uploadPath + new SimpleDateFormat("yyyyMMdd").format(Calendar.getInstance().getTime()) + "/";
        // 拼接文件路径
        String storagePath = BUCKET + "/" + file.getOriginalFilename();

        //如果文件夹不存在则创建
        Path directoryFilePath = Paths.get(BUCKET);
        if (!Files.isDirectory(directoryFilePath, LinkOption.NOFOLLOW_LINKS) && !Files.exists(directoryFilePath, LinkOption.NOFOLLOW_LINKS)) {
            try {
                //创建多层目录用这个方法,用Files.createDirectory方法只能创建一层目录。
                Files.createDirectories(directoryFilePath);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        //判断文件是否存在,存在先删除文件。
        Path path = Paths.get(storagePath);
        if (Files.exists(path, LinkOption.NOFOLLOW_LINKS)) {
            try {
                Files.delete(path);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        //这里使用了 try-with-resource 语法,该语句确保了每个资源,在语句结束时关闭。try块退出时,会自动调用res.close()方法,关闭资源。
        //try-with-resource中的代码一般放的是对资源的申请,如果{}中的代码出项了异常,()中的资源就会被关闭,这在inputstream和outputstream的使用中会很方便。
        try (
                // JDK8 TWR 不能关闭外部资源的,参数传进来的inputStream属于外部资源,我这里定义一个内部的变量来接收这个外部的流。从而达到关闭外部流的效果。
                InputStream innerInputStream = file.getInputStream();
                FileOutputStream outputStream = new FileOutputStream(new File(storagePath))
        ) {

            // 拷贝缓冲区
            byte[] buffer = new byte[1024];
            // 读取文件流长度
            int len;
            // 循环读取inputStream中数据写入到outputStream
            while ((len = innerInputStream.read(buffer)) > 0) {
                outputStream.write(buffer, 0, len);
            }

            // 冲刷流
            outputStream.flush();

        } catch (Exception e) {
            System.out.println("文件上传失败!");
            throw new BusinessException(ErrorCodeEnum.FILE_UPLOAD_FAILURE, e);
        }
        return  responseMap;
    }
    
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

lvdapiaoliang

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

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

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

打赏作者

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

抵扣说明:

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

余额充值