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


Posted in HTML / CSS onJune 06, 2013

先上代码,写的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;
}
}
}
HTML / CSS 相关文章推荐
基于css3仿造window7的开始菜单
Jun 17 HTML / CSS
CSS3 制作旋转的大风车(充满童年回忆)
Jan 30 HTML / CSS
css3实例教程 一款纯css3实现的环形导航菜单
Oct 20 HTML / CSS
CSS3圆角和渐变2种常用功能详解
Jan 06 HTML / CSS
css3实现文字首尾衔接跑马灯的示例代码
Oct 16 HTML / CSS
css3弹性盒子flex实现三栏布局的实现
Nov 12 HTML / CSS
用HTML5 Canvas API中的clearRect()方法实现橡皮擦功能
Mar 15 HTML / CSS
HTML5中视频音频的使用详解
Jul 07 HTML / CSS
HTML5之WebGL 3D概述(上)—WebGL原生开发开启网页3D渲染新时代
Jan 31 HTML / CSS
HTML5 创建canvas元素示例代码
Jun 04 HTML / CSS
H5 meta小结(前端必看篇)
Aug 24 HTML / CSS
css常用字体属性与背景属性介绍
Feb 28 HTML / CSS
将HTML5 Canvas的内容保存为图片借助toDataURL实现
May 20 #HTML / CSS
仿酷狗html5手机音乐播放器主要部分代码
May 15 #HTML / CSS
基于HTML5 Canvas:字符串,路径,背景,图片的详解
May 09 #HTML / CSS
使用HTML5做个画图板的方法介绍
May 03 #HTML / CSS
基于第一个PhoneGap(cordova)的应用详解
May 03 #HTML / CSS
HTML5 离线应用之打造零请求、无流量网站的解决方法
Apr 25 #HTML / CSS
HTML5 本地存储之如果没有数据库究竟会怎样
Apr 25 #HTML / CSS
You might like
PHP项目开发中最常用的自定义函数整理
2010/12/02 PHP
php的日期处理函数及uchome的function_coomon中日期处理函数的研究
2011/01/12 PHP
php 批量替换程序的具体实现代码
2013/10/04 PHP
php实现把数组按指定的个数分隔
2014/02/17 PHP
yii2简单使用less代替css示例
2017/03/10 PHP
php的扩展写法总结
2019/05/14 PHP
js汉字排序问题 支持中英文混排,兼容各浏览器,包括CHROME
2011/12/20 Javascript
js行号显示的文本框实现效果(兼容多种浏览器 )
2015/10/23 Javascript
jQuery内存泄露解决办法
2016/12/13 Javascript
利用JS制作万年历的方法
2017/08/16 Javascript
node.js 利用流实现读写同步,边读边写的方法
2017/09/11 Javascript
微信小程序实现选项卡效果
2018/11/06 Javascript
JS实现灯泡开关特效
2020/03/30 Javascript
JS严格模式原理与用法实例分析
2020/04/27 Javascript
关于vue3默认把所有onSomething当作v-on事件绑定的思考
2020/05/15 Javascript
给Python的Django框架下搭建的BLOG添加RSS功能的教程
2015/04/08 Python
python删除不需要的python文件方法
2018/04/24 Python
利用python将图片版PDF转文字版PDF
2019/05/03 Python
Python qrcode 生成一个二维码的实例详解
2020/02/12 Python
Python任务自动化工具tox使用教程
2020/03/17 Python
python实现音乐播放和下载小程序功能
2020/04/26 Python
TensorFlow keras卷积神经网络 添加L2正则化方式
2020/05/22 Python
python的help函数如何使用
2020/06/11 Python
matplotlib之pyplot模块之标题(title()和suptitle())
2021/02/22 Python
法国家具及室内配件店:home24
2017/01/21 全球购物
SQL语言面试题
2013/08/27 面试题
介绍一下HTTP、HTTPS和SSL
2012/12/16 面试题
系统管理员的职责包括那些?管理的对象是什么?
2016/09/20 面试题
英文翻译的自我评价语句
2013/10/04 职场文书
研究生自我鉴定范文
2013/10/30 职场文书
英语专业应届生求职信范文
2013/11/15 职场文书
幼儿园运动会加油词
2014/02/14 职场文书
企业宣传工作方案
2014/06/02 职场文书
购房协议书范本
2014/10/02 职场文书
运动会3000米加油稿
2015/07/21 职场文书
《堡垒之夜》联动《刺客信条》 4月7日正式上线
2022/04/06 其他游戏