JavaWeb实现文件上传功能

JavaWeb实现文件上传功能

一、前台

1.使用input标签的完成选择文件

input 类型设置成file ,前台即可选择文件

  
          <input name="name" type="text" />
          <br> 
          <input name="name1"type="text" /> 
          <br> 
          <input name="File1" type="file" multiple value="kkkkk"/><br> <input
              type="submit" value="Upload" />
  ​

效果如下:

2.提交请求

模拟表单提交 为啥不适用ajax原因可以看文件下载功能实现链接  https://blog.csdn.net/qq_36657997/article/details/80859634中关于ajax的解释

  
      var blob = new Blob([ fb ]);
      var fd = new FormData();
      this.fb = fb;
      fd.append('file', blob);
      fd.append('fname', encodeURI(f.name));
      fd.append('flen', f.size);
      // extra parameters, it is object format
      this.opt = this.parent.extpara;
      if (this.opt != undefined && this.opt != null && this.opt != "") {
          for (x in this.opt) {
              fd.append(x, this.opt[x]);
          }
      }
      var xhr = new XMLHttpRequest();
      xhr.open('post', this.url, true);
      xhr.onreadystatechange = function(e) {
          if (xhr.readyState == 4 && xhr.status == 200) {
                      if (onSuccess) {
                          onSuccess(data);
                      }
                  }
              }
  ​
          }
      }
      xhr.send(fd);

二、后台

1.获取前台传来的文件

2.利用File类,将文件写到指定位置,完成上传

  
      private String updateFile(String oid, String pid, String vid, String fid, String fname, byte[] file, String project,
              String dirName, String path) throws IOException {
          String destination = "D:/data";
          
          File f = new File(destination + "/" + fname);
          if (!f.exists()) {
              FileUtil.createDir(destination);
              FileUtil.writeFile(file, destination, fname);
          }
          return "success";
      }
  ​
  /**
  * writeFile工具类如下所示
  */
      public static void writeFile(byte[] bytes, String dest, String filename) throws IOException {
          BufferedOutputStream buffStream = new BufferedOutputStream(new FileOutputStream(dest + "/" + filename));
          buffStream.write(bytes);
          buffStream.close();
      }
  ​

猜你喜欢

转载自blog.csdn.net/qq_36657997/article/details/81511685