欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

HTML5拖拽文件到浏览器并实现文件上传下载功能代码

程序员文章站 2023-12-10 15:24:52
使用HTML5拖拽文件到浏览器并实现文件上传下载,html5的功能是越来越强大了,下面与大家分享下具体的实现代码,感兴趣的朋友可以参考下哈... 13-06-06...

先上代码,写的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;
}
}
}