ssm框架文件上传

有两种方法

第一种

上传单个文件:

@RequestMapping("/addfile1")
    public String addfile(@RequestParam("file")MultipartFile file)throws Exception{
        String  path="E:/idea/_1111/src/main/webapp/statics";
        String newfile=FilenameUtils.concat(path,file.getOriginalFilename());
        file.transferTo(new File(newfile));
        return "inputfile";

这个方法的有点就是简单快速,但缺点就是不能更改上传的文件名。原理是直接把文件改变一个储存位置。

第二种:

上传单个文件

 @RequestMapping("/addfile")
    public String addfile(@RequestParam("file")MultipartFile file, Model model)throws Exception{
      String  path="E:/idea/_1111/src/main/webapp/statics";
       File updatefile=new File(path);
       if (!updatefile.exists()){
           updatefile.mkdir();
       }
       String filename=file.getOriginalFilename();
       int intt=filename.lastIndexOf(".");
      String str=filename.substring(intt);
       String newfilename= UUID.randomUUID()+str;
       newfilename=newfilename.replace("-","");
       OutputStream out=new FileOutputStream(new File(path+File.separator+newfilename));
       InputStream input=file.getInputStream();
       byte [] b=new byte[1024];
       int len=0;
       int temn=0;
       while ((temn=input.read())!=-1){
           out.write(b,0,temn);
        }
        out.close();
       input.close();


        return "inputfile";
}

这种方法是把旧文件读出再写入新文件,再更改一下文件名,使用UUID伪随机。

上传多个文件

@RequestMapping("/addfile")
    public String addfile(@RequestParam("file")MultipartFile files[], Model model)throws Exception{
      String  path="E:/idea/_1111/src/main/webapp/statics";
       File updatefile=new File(path);
       if (!updatefile.exists()){
           updatefile.mkdir();
       }
        List<String> lii=new ArrayList<String>();
       for(int i=0;i<files.length;i++) {
           String filename = files[i].getOriginalFilename();
           int intt = filename.lastIndexOf(".");
           String str = filename.substring(intt);
           String newfilename = UUID.randomUUID() + str;
           newfilename = newfilename.replace("-", "");

           OutputStream out = new FileOutputStream(new File(path + File.separator + newfilename));
           InputStream input = files[i].getInputStream();
           byte[] b = new byte[1024];
     int temn = 0;
           while ((temn = input.read(b)) != -1) {
               out.write(b, 0, temn);
           }
           out.close();
           input.close();
           lii.add(newfilename);
       }
       model.addAttribute("file",lii);


        return "inputfile";

    }

可以插入多个文件。用一个file数组接收。

世间种种的诱惑,不惊不扰我清梦
原文地址:https://www.cnblogs.com/javalisong/p/9522571.html