Java實現HTML5拖拽檔案上傳

來源:互聯網
上載者:User

標籤:

這是首頁面

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head> <base href="<%=basePath%>"> <title>HTML5檔案拖動上傳</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <style type="text/css"> .up { width:600px; height:100px; border: 1px solid; text-align: center; line-height: 100px; color: #72FD31; } .ne { width:600px; height:400px; border: 1px solid; margin-top:20px } </style> </head> <body> <div style="margin: 20px 400px"> <div class="up" id="upflies">將檔案拖拽到此處上傳</div> <div class="ne" id="content1"></div> </div> <script type="text/javascript"> //1:檔案上傳html5 //知識點:drag 把檔案拖拽到瀏覽器的預設行為是下載或開啟 document.ondragleave = function(e) { e.preventDefault(); //拖動元素離開的事件 }; document.ondrop = function(e) { e.preventDefault(); //檔案拖放鬆開以後的事件 }; document.ondragover = function(e) { e.preventDefault(); }; function tm_upload() { //2:通過html5拖拽事件,ondrop,然後通過拖動地區監聽瀏覽器的drop事件達到檔案上傳的目的 var uploadArea = document.getElementById("upflies"); //監聽檔案上傳地區的檔案鬆開事件 uploadArea.addEventListener("drop", function(e) { e.preventDefault(); //3:從事件event中擷取拖拽到瀏覽器的檔案資訊 //擷取事件的檔案清單資訊 var fileList = e.dataTransfer.files; var length = fileList.length; for(var i=0;i<length;i++) { //alert(fileList[i].type); //顯示上傳檔案的類型 //獲得圖片流 var img = window.webkitURL.createObjectURL(fileList[i]); //Firefox不支援! //擷取檔案名稱 var fileName = fileList[i].name; //擷取檔案的大小 var fileSize = fileList[i].size; var str = "<div><img src=‘"+img+"‘ height=‘20%x‘ width=‘20%‘ /><p>檔案名稱:"+fileName+"</p><p>大小:"+fileSize+"<p/></div>" document.getElementById("content1").innerHTML +=str; //4:通過XMLHttpRequest上傳檔案到伺服器 var xhr = new XMLHttpRequest(); xhr.open("post", "data.jsp",true); //代表非同步提交,false表示非非同步 //判斷是不是一個ajax xhr.setRequestHeader("X-Requested-with", "XMLHttpRequest"); //5:通過HTML5 FormData動態設定表單元素 var formdata = new FormData(); //動態給表單賦值,傳遞二進位檔案 //6:擷取伺服器上的檔案資訊 formdata.append("doc",fileList[i]); //7:編寫data.jsp上傳頁面 xhr.send(formdata); } }); } tm_upload(); </script> </body></html>

- - -- - -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -- - - - -- - -- - - - - - - - - -
data.jsp  這裡是處理頁面

<%@page import="java.io.File"%><%@page import="org.apache.commons.fileupload.FileItem"%><%@page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%><%@page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%><%@page import="org.apache.commons.fileupload.FileItemFactory"%><%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%    /*        1:檔案上傳jar包        2:建立伺服器目錄 upload        3:從request對象擷取我們ajax傳輸的檔案資訊        4:將用戶端傳遞過來的檔案上傳到 upload目錄下            a:一定要對檔案重新命名?,檔案不支援中文    */        //設定編碼    request.setCharacterEncoding("UTF-8");    response.setCharacterEncoding("UTF-8");        //擷取伺服器的根目錄     String rootPath = request.getRealPath("/");    System.out.println("伺服器路徑:"+rootPath);    String uploadPath = rootPath+"/upload";    File file  = new File(uploadPath);    //自動建立目錄    if(!file.exists()){file.mkdirs();}        //判斷是否存在這個檔案夾        //建立一個檔案對象工廠    FileItemFactory factory = new DiskFileItemFactory();    ServletFileUpload upload = new ServletFileUpload(factory);    //從請求對象中擷取檔案資訊    List  items = upload.parseRequest(request);    if (items!=null) {        Iterator iterator =items.iterator();        while (iterator.hasNext()) {            FileItem item = (FileItem)iterator.next();            //判斷是否為表單裡提交上來的            if (item.isFormField()){                continue;            }else{                String fileName = item.getName();                long size = item.getSize();                System.out.println(fileName+" - - - "+size);                //檔案上傳到伺服器                int pos = fileName.lastIndexOf(".");                                //擷取檔案尾碼                String ext = fileName.substring(pos,fileName.length());                fileName = UUID.randomUUID().toString()+ext;                File saveFile = new File(uploadPath,fileName);                //上傳                item.write(saveFile);                            }        }    }    %>

Commons-FileupLoad.jar 下載:http://pan.baidu.com/s/1o6FpGHc

 

 

 

Java實現HTML5拖拽檔案上傳

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.