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 相关文章推荐
详解CSS的border边框属性及其在CSS3中的新特性
May 10 HTML / CSS
css3实例教程 一款纯css3实现的环形导航菜单
Oct 20 HTML / CSS
css3 中的新特性加强记忆详解
Apr 16 HTML / CSS
CSS 说明横向进度条最后显示文字的实现代码
Nov 10 HTML / CSS
HTML5的Geolocation地理位置定位API使用教程
May 12 HTML / CSS
利用HTML5画出一个坦克的形状具体实现代码
Jun 20 HTML / CSS
Html5 Canvas动画基础碰撞检测的实现
Dec 06 HTML / CSS
HTML5 客户端数据库简易使用:IndexedDB
Dec 19 HTML / CSS
canvas小画板之平滑曲线的实现
Aug 12 HTML / CSS
AmazeUI框架搭建的方法步骤(图文)
Aug 17 HTML / CSS
浅析HTML5 meta viewport参数
Oct 28 HTML / CSS
微信小程序纯CSS实现无限弹幕滚动效果
Sep 23 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获取网址的顶级域名函数代码
2012/09/24 PHP
php模板函数 正则实现代码
2012/10/15 PHP
PHP内核探索:变量概述
2014/01/30 PHP
PHP与服务器文件系统的简单交互
2016/10/21 PHP
PHP基于rabbitmq操作类的生产者和消费者功能示例
2018/06/16 PHP
理解JavaScript中的事件
2006/09/23 Javascript
简单三步,搞掂内存泄漏
2007/03/10 Javascript
node.js中的querystring.escape方法使用说明
2014/12/10 Javascript
js随机生成字母数字组合的字符串 随机动画数字
2015/09/02 Javascript
JavaScript实现in-place思想的快速排序方法
2016/08/07 Javascript
jQuery在ie6下无法设置select选中的解决方法详解
2016/09/20 Javascript
jquery二级目录选中当前页的css样式
2016/12/08 Javascript
利用Vue实现移动端图片轮播组件的方法实例
2017/08/23 Javascript
Angular中支持SCSS的方法
2017/11/18 Javascript
JavaScript常用数学函数用法示例
2018/05/14 Javascript
D3.js的基础部分之数组的处理数组的排序和求值(v3版本)
2019/05/09 Javascript
Bootstrap 时间日历插件bootstrap-datetimepicker配置与应用小结
2019/05/28 Javascript
使用easyui从servlet传递json数据到前端页面的两种方法
2019/09/05 Javascript
layui异步加载table表中某一列数据的例子
2019/09/16 Javascript
解决Idea、WebStorm下使用Vue cli脚手架项目无法使用Webpack别名的问题
2019/10/11 Javascript
使用IPython来操作Docker容器的入门指引
2015/04/08 Python
Python导入模块时遇到的错误分析
2017/08/30 Python
python从入门到精通 windows安装python图文教程
2019/05/18 Python
python通过TimedRotatingFileHandler按时间切割日志
2019/07/17 Python
使用python远程操作linux过程解析
2019/12/04 Python
python无序链表删除重复项的方法
2020/01/17 Python
python爬虫开发之PyQuery模块详细使用方法与实例全解
2020/03/09 Python
解决Keras的自定义lambda层去reshape张量时model保存出错问题
2020/07/01 Python
详解Pycharm与anaconda安装配置指南
2020/08/25 Python
详解webapp页面滚动卡顿的解决办法
2018/12/26 HTML / CSS
数控专业毕业生自荐信范文
2014/03/04 职场文书
医学检验专业自荐信
2014/09/18 职场文书
2015年初中元旦晚会活动总结
2014/11/28 职场文书
男人帮观后感
2015/06/18 职场文书
庭外和解协议书
2016/03/23 职场文书
pytorch 两个GPU同时训练的解决方案
2021/06/01 Python