SpringMVC文件上传(文件名不重复)


1)表单项type=“file”
2)表单的提交方式是post
3)表单的enctype属性是多部分表单形式,及enctype=“multipart/form-data”

单文件上传步骤
1)导入fileupload和io坐标
2)配置文件上传解析器
3)编写文件上传代码

   
      commons-fileupload
      commons-fileupload
      1.4
    
    
      commons-io
      commons-io
      1.4
    
   
        
        
        
        
        
    >

编写业务层 Controller 上传代码

@RequestMapping(value = "mmm")
    @ResponseBody
    public String  say12(MultipartFile files) throws IOException {
        String filen = files.getOriginalFilename();

        File file = new File("H:\\"+filen);
        int i = 0;
        while (file.exists()){
            i++;
            file = new File("H:\\"+i+filen); //如果文件存在名称相同的则加前缀或者加时间戳

        }
        file.createNewFile();
        InputStream ins = files.getInputStream();
        BufferedInputStream bis =new BufferedInputStream(ins);
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
        byte[] by =new byte[1024];
        int len;
        while ((len = bis.read(by)) != -1){
                bos.write(by);
        }
        bos.close();
        bis.close();
        return "Successupload!";
    }

form表单

上传结果