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中背景尺寸background-size详解
Sep 02 HTML / CSS
纯css3实现的竖形无限级导航
Dec 10 HTML / CSS
详解CSS3 rem(设置字体大小) 教程
Nov 21 HTML / CSS
利用CSS3动画实现圆圈由小变大向外扩散的效果实例
Sep 10 HTML / CSS
CSS3动画特效在活动页中的应用
Jan 21 HTML / CSS
CSS3 实现图形下落动画效果
Nov 13 HTML / CSS
借助HTML5 Canvas来绘制三角形和矩形等多边形的方法
Mar 14 HTML / CSS
canvas实现俄罗斯方块的方法示例
Dec 13 HTML / CSS
HTML5验证以及日期显示的实现详解
Jul 05 HTML / CSS
HTML5几个设计和修改的页面范例分享
Sep 29 HTML / CSS
amazeui 验证按钮扩展的实现
Aug 21 HTML / CSS
CSS3实现的水平标题菜单
Apr 14 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
实时抓取YAHOO股票报价的代码
2006/10/09 PHP
PHP实现今天是星期几的几种写法
2013/09/26 PHP
Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 2611816 bytes)
2014/11/08 PHP
php利用gd库为图片添加水印
2016/11/09 PHP
PHP中模糊查询并关联三个select框
2017/06/19 PHP
Js+XML 操作
2006/09/20 Javascript
div移动 输入框不能输入的问题
2009/11/19 Javascript
extjs 初始化checkboxgroup值的代码
2011/09/21 Javascript
原生js实现查找/添加/删除/指定元素的class
2013/04/12 Javascript
自动刷新网页,自动刷新当前页面,JS调用
2013/06/24 Javascript
javascript的parseFloat()方法精度问题探讨
2013/11/26 Javascript
使用jQuery管理选择结果
2015/01/20 Javascript
javascript中tostring()和valueof()的用法及两者的区别
2015/11/16 Javascript
Vue.JS入门教程之自定义指令
2016/12/08 Javascript
Jquery Easyui选项卡组件Tab使用详解(10)
2016/12/18 Javascript
vue组件实例解析
2017/01/10 Javascript
express中static中间件的具体使用方法
2019/10/17 Javascript
Layui表格监听行单双击事件讲解
2019/11/14 Javascript
如何解决vue在ios微信&quot;复制链接&quot;功能问题
2020/03/26 Javascript
详解node.js创建一个web服务器(Server)的详细步骤
2021/01/15 Javascript
[38:51]2014 DOTA2国际邀请赛中国区预选赛 Orenda VS LGD-CDEC
2014/05/22 DOTA
python+opencv打开摄像头,保存视频、拍照功能的实现方法
2019/01/08 Python
Python3.5实现的三级菜单功能示例
2019/03/25 Python
深入浅析css3 中display box使用方法
2015/11/25 HTML / CSS
美国猫狗药物和用品网站:PetCareRx
2017/01/05 全球购物
百联网上商城:i百联
2017/01/28 全球购物
运动鞋、街头服装、手表和手袋的实时市场:StockX
2020/11/25 全球购物
大三预备党员入党思想汇报
2014/01/08 职场文书
打架检讨书100字
2014/01/08 职场文书
公司业务员岗位职责
2014/03/18 职场文书
人事任命书怎么写
2014/06/05 职场文书
2019大学生社会实践报告汇总
2019/08/16 职场文书
最新农村养殖致富:资金投入较低的创业项目有哪些?
2019/09/26 职场文书
MySQL 使用SQL语句修改表名的实现
2021/04/07 MySQL
Python趣味挑战之实现简易版音乐播放器
2021/05/28 Python
Three.js实现雪糕地球的使用示例详解
2022/07/07 Javascript