DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> HTML基礎知識 >> HTML5詳解 >> HTML5拖拽文件到浏覽器並實現文件上傳下載功能代碼
HTML5拖拽文件到浏覽器並實現文件上傳下載功能代碼
編輯:HTML5詳解     

先上代碼,寫的JSP頁面,後台是tomcat服務器,所以頁面裡有一些Java的代碼,如果後台用其他語言可以無視: 

復制代碼代碼如下:
<%@ page language="Java" contentType="text/Html; charset=UTF-8" 
pageEncoding="UTF-8"%> 
<%@page import="Java.io.*"%> 
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/Html4/loose.dtd"> 
<Html> 
<head> 
<meta http-equiv="Content-Type" content="text/Html; charset=UTF-8"> 
<title>上傳、下載文件</title> 
<style type="text/CSS"> 
#filedrag { 
display: none; 
font-weight: bold; 
text-align: center; 
padding: 1em 0; 
margin: 1em 0; 
color: #555; 
border: 2px dashed #555; 
border-radius: 7px; 
cursor: default; 

#filedrag.hover { 
color: #f00; 
border-color: #f00; 
border-style: solid; 
box-shadow: inset 0 3px 4px #888; 

</style> 
</head> 
<body> 
<form id="upload" action="UploadServlet" enctype="multipart/form-data" 
method="post" onsubmit="return upLoad();"> 
<p> 
<label for="fileselect">file name:</label><input multiple="true" 
type="file" id="fileselect" name="fileselect[]" /> 
<div id="filedrag">或者將文件拖拽到這裡</div> 
<div id="submitbutton"> 
<input type="submit" value="提交"> 
</div> 
</form> 
<div id="messages"> 
</div> 
<% //Java代碼,顯示服務器上可以供下載的文件 
File f = new File("G://defggg/"); 
File[] list = f.listFiles(); 
for (int i = 0; i < list.length; ++i) { 
System.out.println(list[i].getName()); 
out.print("<a href='DownloadServlet?filename=" 
+ list[i].getName() + "'>" + list[i].getName() 
+ "</a><br/>"); 

%> 
<script type="text/Javascript"> 
var upfiles = new Array(); 
// getElementById 
function $id(id) { 
return document.getElementById(id); 

// output information 
function Output(msg) { 
var m = $id("messages"); 
m.innerHTML = msg + m.innerHtml; 

// file drag hover 
function FileDragHover(e) { 
e.stopPropagation(); 
e.preventDefault(); 
e.target.className = (e.type == "dragover" ? "hover" : ""); 

// file selection 
function FileSelectHandler(e) { 
// cancel event and hover styling 
FileDragHover(e); 
// fetch FileList object 
var files = e.target.files || e.dataTransfer.files; 
// process all File objects 
for ( var i = 0, f; f = files[i]; i++) { 
ParseFile(f); 
upfiles.push(f); 


// output file information 
function ParseFile(file) { 
Output("<p>文件信息: <strong>" + file.name 
+ "</strong> 類型: <strong>" + file.type 
+ "</strong> 大小: <strong>" + file.size 
+ "</strong> bytes</p>"); 

function upLoad() { 
if (upfiles[0]) { 
var xhr = new XMLHttpRequest(); //AJax異步傳輸數據 
xhr.open("POST", "UploadServlet", true); 
var formData = new FormData(); 
for ( var i = 0, f; f = upfiles[i]; i++) { 
formData.append('myfile', f); 

xhr.send(formData); 
xhr.onreadystatechange=function(e){ 
history.go(0); //由於這個頁面還要顯示可以下載的文件,所以需要刷新下頁面 

return false; 


// initialize 
function Init() { 
var fileselect = $id("fileselect"), filedrag = $id("filedrag"), submitbutton = $id("submitbutton"); 
// file select 
fileselect.addEventListener("change", FileSelectHandler, false); 
// is XHR2 available? 
var xhr = new XMLHttpRequest(); 
if (xhr.upload) { 
// file drop 
filedrag.addEventListener("dragover", FileDragHover, false); 
filedrag.addEventListener("dragleave", FileDragHover, false); 
filedrag.addEventListener("drop", FileSelectHandler, false); 
filedrag.style.display = "block"; 
// remove submit button 
//submitbutton.style.display = "none"; 


// call initialization file 
if (window.File && window.FileList && window.FileReader) { 
Init(); 

</script> 
</body> 
</Html> 

附上後台處理上傳下載的servlet,用了smartUpLoad,不能很好的解決中文問題: 

復制代碼代碼如下:
package com.hit.software; 
import Java.io.IOException; 
import Javax.servlet.ServletConfig; 
import Javax.servlet.ServletException; 
import Javax.servlet.annotation.WebServlet; 
import Javax.servlet.http.HttpServlet; 
import Javax.servlet.http.HttpServletRequest; 
import Javax.servlet.http.HttpServletResponse; 
import com.JSPsmart.upload.Files; 
import com.JSPsmart.upload.SmartUpload; 
/** 
* Servlet implementation class UploadServlet 
*/ 
@WebServlet("/UploadServlet") 
public class UploadServlet extends HttpServlet { 
private static final long serialVersionUID = 1L; 
private ServletConfig config; 
final public void init(ServletConfig config) throws ServletException { 
this.config = config; 

/** 
* @see HttpServlet#HttpServlet() 
*/ 
public UploadServlet() { 
super(); 
// TODO Auto-generated constructor stub 

/** 
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse 
* response) 
*/ 
protected void doGet(HttpServletRequest request, 
HttpServletResponse response) throws ServletException, IOException { 
doPost(request, response); 

/** 
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse 
* response) 
*/ 
protected void doPost(HttpServletRequest request, 
HttpServletResponse response) throws ServletException, IOException { 
request.setCharacterEncoding("UTF-8"); 
// String s = request.getParameter("pic"); 
// System.out.println(s); 
SmartUpload mySmartUpload = new SmartUpload(); 
try { 
mySmartUpload.initialize(config, request, response); 
mySmartUpload.setMaxFileSize(150 * 1024 * 1024); 
mySmartUpload.setTotalMaxFileSize(150 * 1024 * 1024); 
// mySmartUpload.setAllowedFilesList("doc,txt,rar,pdf,png"); 
mySmartUpload.setDenIEdFilesList("exe"); 
mySmartUpload.upload(); 
Files f = mySmartUpload.getFiles(); 
int size = f.getCount(); 
for (int i = 0; i < size; ++i) { 
String fileName = mySmartUpload.getFiles().getFile(i) 
.getFileName(); 
fileName = new String(fileName.trim().getBytes(), "UTF-8"); //能解決部分中文問題 
System.out.println("filename=" + fileName); 
if (!fileName.equals("")) { 
String path = "g:/defggg/" + fileName; 
f.getFile(i).saveAs(path, SmartUpload.SAVE_PHYSICAL); 


} catch (Exception e) { 
e.printStackTrace(); 
System.out.println("Unable to upload the file."); 
System.out.println("Error :" + e.toString()); 

response.sendRedirect("index.JSP"); 




復制代碼代碼如下:
package com.hit.software; 
import Java.io.File; 
import Java.io.IOException; 
import Javax.servlet.ServletConfig; 
import Javax.servlet.ServletException; 
import Javax.servlet.annotation.WebServlet; 
import Javax.servlet.http.HttpServlet; 
import Javax.servlet.http.HttpServletRequest; 
import Javax.servlet.http.HttpServletResponse; 
import Javax.servlet.JSp.JSPFactory; 
import Javax.servlet.JSp.JSPWriter; 
import Javax.servlet.JSP.PageContext; 
import com.JSPsmart.upload.SmartUpload; 
import com.JSPsmart.upload.SmartUploadException; 
/** 
* Servlet implementation class DownloadServlet 
*/ 
@WebServlet("/DownloadServlet") 
public class DownloadServlet extends HttpServlet { 
private static final long serialVersionUID = 1L; 
private ServletConfig config; 
/** 
* @see HttpServlet#HttpServlet() 
*/ 
public DownloadServlet() { 
super(); 
// TODO Auto-generated constructor stub 

final public void init(ServletConfig config) throws ServletException { 
this.config = config; 

/** 
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse 
* response) 
*/ 
protected void doGet(HttpServletRequest request, 
HttpServletResponse response) throws ServletException, IOException { 
doPost(request, response); 

/** 
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse 
* response) 
*/ 
protected void doPost(HttpServletRequest request, 
HttpServletResponse response) throws ServletException, IOException { 
request.setCharacterEncoding("UTF-8"); 
String fileName = request.getParameter("filename"); 
System.out.println("down :"+fileName); 
if (fileName == null) { 
response.sendRedirect("index.JSP"); 
return; 

fileName = "G://defggg//" + fileName; 
File f = new File(fileName); 
if (f.exists() && f.isFile()) { 
SmartUpload su = new SmartUpload(); 
su.initialize(config, request, response); 
su.setContentDisposition(null); 
try { 
su.downloadFile(fileName); 
} catch (SmartUploadException e) { 
// TODO Auto-generated catch block 
e.printStackTrace(); 

} else { 
response.sendRedirect("index.JSP"); 
return; 


XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved