Java實現拖拽上傳

來源:互聯網
上載者:User

標籤:i++   item   data   拖拽上傳   border   append   java實現   mkdir   傳遞   

原文:http://www.open-open.com/code/view/1437358795584

 

在項目開發中由於實際需求,需要開發拖拽上傳的功能,ok!

 

先看:

jsp上傳前端代碼:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>      <!DOCTYPE html>      <html>      <head>      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">      <title>小夜的傳說最新力作!</title>      <style type="text/css">      * {          padding: 0px;          margin: 0px;      }            body {          background: #394E48;          font-size: 14px;          font-family: "微軟雅黑";      }            .title {          text-align: center;          color: #fff;          margin-top: 50px;      }            .demo {          width: 900px;          height: 140px;          margin: 50px auto;      }            .drag-area {          width: 100%;          height: 100px;          border: 3px dashed #fff;          text-align: center;          line-height: 100px;          color: #fff;          font-size: 36px;          font-weight: 700;      }            }      .preview div {          width: 195px;          overflow: hidden;          border: 1px dashed silver;          margin-top: 10px;          float: left;          padding: 9px;          text-align: center;          height: 168px;      }            .preview img {          width: 80px;          height: 80px;      }      </style>      </head>      <body>          <h1 class="title">小夜的傳說最新力作!Java實現拖拽上傳!!</h1>           <div class="demo">              <div class="drag-area" id="upload-area">                  將圖片拖拽到這裡              </div>              <!-- 圖片預覽 -->              <div id="preview" class="preview"></div>           </div>      </body>      <script type="text/javascript">          //1、檔案上傳HTML5 通過drag把檔案拖拽到瀏覽器的預設事件覆蓋          //檔案離開          document.ondragleave=function(e){          e.preventDefault();              console.info("檔案離開執行了我!!");          };          //滑鼠鬆開檔案          document.ondrop=function(e){          e.preventDefault();              console.info("鬆開以後執行了我!");          };          //滑鼠移動檔案          document.ondragover=function(e){          e.preventDefault();              console.info("檔案移動以後執行了我!");          };                    function tm_upload(){              var img1="";              var uploadArea=document.getElementById("upload-area");              //2、通過HTML5拖拽事件,ondrop,然後通過拖動地區監聽瀏覽器的drop事件達到檔案上傳的目的              uploadArea.addEventListener("drop", function(e){                  e.preventDefault();                  //3、從事件event中擷取拖拽到瀏覽器的檔案資訊                  var fileList=e.dataTransfer.files;                  for(var i=0;i<fileList.length;i++){                      //此處判斷只能上傳圖片                      if(fileList[i].type.indexOf("image")!=0){                          alert("請上傳圖片");                          return;                                   }                      //圖片預覽  這一步需要判斷是什麼瀏覽器  大家自己判斷吧                      /*************************************/                      img1=window.URL.createObjectURL(fileList[i]);                      /*************************************/                      var str="<div><img src=‘"+img1+"‘/><p>"+fileList[i].name+"</p></div>";                      document.getElementById("preview").innerHTML +=str;                                            var fileName=fileList[i].name;                      console.info(fileName);                      var fileSize=fileList[i].size;                      console.info(fileSize);                      //4、通過XMLHttpRequest上傳檔案到伺服器  就是一個ajax請求                      var xhr=new XMLHttpRequest();                      //5、這裡需要先寫好一個data.jsp的上傳檔案,當然,你寫成servlet或者是action都可以                      xhr.open("post","data.jsp",true);                      xhr.setRequestHeader("X-Request-Width", "XMLHttpRequest");                      //6、通過HTML5 FormData動態設定表單元素                      var formData=new FormData();//動態給表單賦值,傳遞二進位檔案                      //其實就相當於<input type="file" name="file"/>                      formData.append("doc",fileList[i]);                      xhr.send(formData);                  }              });          }          //直接調用          tm_upload();      </script>      </html>  

 

ok,編寫完前台代碼,在寫後台,如下:

 <%@page import="java.util.UUID"%>      <%@page import="org.apache.commons.fileupload.FileItem"%>      <%@page import="java.util.Iterator"%>      <%@page import="java.util.List"%>      <%@page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%>      <%@page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%>      <%@page import="org.apache.commons.fileupload.FileItemFactory"%>      <%@page import="java.io.File"%>      <%@ page language="java" contentType="text/html; charset=UTF-8"          pageEncoding="UTF-8"%>      <%      /*      1、檔案上傳:            */      request.setCharacterEncoding("utf-8");      response.setCharacterEncoding("utf-8");      //擷取檔案路徑      String strPath=request.getRealPath("/")+"/upload";      File file =new File(strPath);      if(!file.exists())file.mkdirs();      FileItemFactory factory=new DiskFileItemFactory();      ServletFileUpload upload=new ServletFileUpload(factory);      //從請求對象中擷取檔案資訊      List items= upload.parseRequest(request);      if(items!=null){          for(int i=0;i<items.size();i++){              Iterator iterator=items.iterator();              while(iterator.hasNext()){              FileItem item=(FileItem)iterator.next();              if(item.isFormField()){                  continue;              }else{                  String fileName=item.getName();                  Long fileSize=item.getSize();                  int pos=fileName.indexOf(".");                  String ext=fileName.substring(pos,fileName.length());                     fileName=UUID.randomUUID().toString()+ext;                  File saveFile=new File(strPath,fileName);                  item.write(saveFile);               }              }          }      }       %>  

 

ok,至此,就完成拖拽上傳的功能,當然這隻是粗略版本,我已將代碼最佳化為外掛程式可以直接使用了!!

 

Java實現拖拽上傳

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.