Postman发送SpringBoot接受文件

SpringBoot 发送文件 的学习

获取SpringBoot的根目录

 ApplicationHome home = new ApplicationHome(getClass());
	File jarFile = home.getSource();
    	String s = jarFile.getParentFile().toString();

获取SpringBoot的目录
File file2 = new File (System.getProperty(“user.dir”));
在这里插入图片描述

创建文件夹

File creatfile = new File(s + File.separator + "fileCenter");     
        if(!creatfile.exists()&& !creatfile.isDirectory()) {
            creatfile.mkdir();
        }

File.separator 这个是// \ 他会自动识别系统 根据不同系统加上 符号

对 MultipartFile file 的操作
理解MultipartFile

注意
(3) getContentType方法

     getContentType方法获取的是文件的类型,注意是文件的类型,不是文件的拓展名。

获取文件的MD5

 try {
            //获取文件的byte信息
            byte[] uploadBytes = file.getBytes();
            // 拿到一个MD5转换器
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            byte[] digest = md5.digest(uploadBytes);
            //转换为16进制
            fi.setFileHashMD5(new BigInteger(1, digest).toString(16));
        } catch (Exception e) {
            log.error(e.getMessage());
        }



保存文件 重复命名的问题
这个里面注意 不能 直接去获取扩展名 那个获取的不是扩展名是文件类型

File savefile = new File(creatfile+File.separator+file.getOriginalFilename());

    String filename = savefile.getName();
    String name = filename.substring(0,filename.indexOf("."));
    //文件后缀,如.jpeg
    String suffix = filename.substring(filename.lastIndexOf("."));
    int i = 1;
    while(savefile.exists()) {
        String newFilename = name + "(" + i + ")" + suffix;
        String parentPath = savefile.getParent();
        savefile = new File(parentPath + File.separator + newFilename);
        i++;

    }

    **file.transferTo(savefile);     //**这个是MultipartFile 的

改进

   if (!"application/octet-stream".equals(fi.getExtion().toString())) {
         File savefile = new File(creatfile + File.separator + file.getOriginalFilename());

         String filename = savefile.getName();
         String name = filename.substring(0, filename.lastIndexOf("."));
         //文件后缀,如.jpeg
         String suffix = filename.substring(filename.lastIndexOf("."));
            int i = 1;
            while (savefile.exists()) {

                String newFilename = name + "(" + i + ")" + suffix;
                String parentPath = savefile.getParent();
                savefile = new File(parentPath + File.separator + newFilename);
                i++;
            }
                try {
                    file.transferTo(savefile);
                } catch (IOException e) {
                    log.error("【文件保存失败】", e);
                    throw new DemoException("文件保存失败,请联系管理员");
                }
        }
        else {
         File savefile = new File(creatfile + File.separator + file.getOriginalFilename());
         String filename = savefile.getName();
         //文件后缀,如.jpeg

            int j = 1;
            while (savefile.exists()) {

                String newFilename = filename + "(" + j + ")";
                String parentPath = savefile.getParent();
                savefile = new File(parentPath + File.separator + newFilename);
                j++;
            }

         try {
             file.transferTo(savefile);
         } catch (IOException e) {
             log.error("【文件保存失败】", e);
             throw new DemoException("文件保存失败,请联系管理员");
         }


首先用DEBUG得到了 无后文件的类型 首先判断是否是无后缀文件
然后如果是 那就不久找后缀 直接名字结尾加重复名字的数字 来解决重复名字问题

然后在上面的代码中 如果有多个点 会出现问题
``

String name = filename.substring(0, filename.lastIndexOf("."));

用这个就可以解决这个问题

顺便记录一下 括号加错地方 让我崩溃的故事…

    while (savefile.exists()) {

                String newFilename = name + "(" + i + ")" + suffix;
                String parentPath = savefile.getParent();
                savefile = new File(parentPath + File.separator + newFilename);
                i++;
            
                try {
                    file.transferTo(savefile);
                } catch (IOException e) {
                    log.error("【文件保存失败】", e);
                    throw new DemoException("文件保存失败,请联系管理员");
                }
        }}


下班 回家

第二天改进

根据秒传的那个原理 先判断MD5是否存在 弄了整整一天 有时候出现许多错误 可能重启一下IDEA就好了 这是真的 我卡了 半天

最终版 首先 我想的是 初始化时候运行一个程序 把已存在的MD5写入文本文档 具体代码如下

遍历该目录下所有文件

public static final StringBuffer strbuf = new StringBuffer();
    public static StringBuffer func(File file) {
        File[] fs = file.listFiles();
        for (File f : fs) {
            if (f.isDirectory()) {    //若是目录,则递归打印该目录下的文件
                func(f);
            }
            if (f.isFile()) {  //若是文件,直接打印
                strbuf.append(f.toString() + "\r\n");
            }
        }
        return strbuf;
    } 

这个里面要注意 那个量要写成常量写在外面

然后读取 分割

 StringBuffer str = func(creatfile);
        String st = str.toString();
        String[] strRating = st.split("\r\n");

特别注意 我最开始 把 下面的\r\n写成了\n\r 让我怀疑了版半天人生

MD5获取

  public static String getMD5(String path) {
        String md5Hex = null;
        try {
            md5Hex = DigestUtils.md5Hex(new FileInputStream(path));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return md5Hex;
    }

集合读取

HashMap<String,String> hm = new HashMap<>();

        for (String s1 : strRating) {
            System.out.println(s1.toString());
            String md5 = getMD5(s1);
            hm.put(md5,s1);
        }

        BufferedWriter bw = new BufferedWriter(new FileWriter(creatfile+File.separator+"Md51.txt",true));

        for(Map.Entry<String,String> entry : hm.entrySet()){
           
            System.out.println(entry.toString());
            bw.write(entry.toString());
            bw.newLine();
            bw.flush();

        }
        bw.close();

遍历文件 把文件内容写了Map

    BufferedReader br = new BufferedReader(new FileReader(creatfile+File.separator+"Md51.txt"));

    HashMap<String,String> stuRead = new HashMap<>();
    String line=null;
    while((line=br.readLine())!=null){
        String regets = "=";
        String key = line.substring(0, line.lastIndexOf(regets));
        //文件后缀,如.jpeg
        System.out.println(key);
        String name =line.substring(line.lastIndexOf(regets)+1);
        System.out.println(name);
        stuRead.put(key,name);

    }
    br.close();
    for(Map.Entry<String,String> entry : stuRead.entrySet()){

        System.out.println(entry.getKey().toString());
        System.out.println(1);
    }

复制粘贴

public static void copyfile(String from, String to) throws IOException {

        BufferedReader br = new BufferedReader(new FileReader(from));


        BufferedWriter bw = new BufferedWriter(new FileWriter(to));

        String line = null;
        **while ((line = br.readLine()) == null) {**     这个地方注意这是错的应该是!=   我写错了
                                                                好几次
            bw.write(line);
            bw.newLine();
            bw.flush();
        }
        br.close();
        bw.close();
    }

一定要注意括号 括号 括号

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值