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和html制作泡沫对话框实现代码
Mar 21 HTML / CSS
用css3写出气球样式的示例代码
Sep 11 HTML / CSS
html通过canvas转成base64的方法
Jul 18 HTML / CSS
20佳惊艳的HTML5应用程序示例分享
May 03 HTML / CSS
HTML5安全介绍之内容安全策略(CSP)简介
Jul 10 HTML / CSS
一张图片能隐含千言万语之隐藏你的程序代码
Dec 13 HTML / CSS
HTML5之HTML元素扩展(上)—新增加的元素及使用概述
Jan 31 HTML / CSS
简单整理HTML5的基本特性和语法
Feb 18 HTML / CSS
HTML5对比HTML4的主要改变和改进总结
May 27 HTML / CSS
Web前端页面跳转并取到值
Apr 24 HTML / CSS
小程序canvas中文字设置居中锚点
Apr 16 HTML / CSS
解析浏览器的一些“滚动”行为鉴赏
Sep 16 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启动windows应用程序、执行bat批处理、执行cmd命令的方法(exec、system函数详解)
2014/10/20 PHP
php魔法函数与魔法常量使用介绍
2017/07/23 PHP
PHP PDOStatement::fetchColumn讲解
2019/01/31 PHP
文字幻灯片
2006/06/26 Javascript
jQuery Lightbox 图片展示插件使用说明
2010/04/25 Javascript
select标签模拟/美化方法采用JS外挂式插件
2013/04/01 Javascript
基于javascipt-dom编程 table对象的使用
2013/04/22 Javascript
JS实现动态给图片添加边框的方法
2015/04/01 Javascript
JavaScript实现添加、查找、删除元素
2015/07/02 Javascript
JQuery的attr 与 val区别
2016/06/12 Javascript
手机端实现Bootstrap简单图片轮播效果
2016/10/13 Javascript
JS实现滑动门效果的方法详解
2016/12/19 Javascript
ionic2懒加载配置详解
2017/09/01 Javascript
学习Vue组件实例
2018/04/28 Javascript
解决vue-cli3 使用子目录部署问题
2018/07/19 Javascript
对angularJs中2种自定义服务的实例讲解
2018/09/30 Javascript
微信小程序获取地理位置及经纬度授权代码实例
2019/09/18 Javascript
jquery 插件重新绑定的处理方法分析
2019/11/23 jQuery
Vuex的API文档说明详解
2020/02/05 Javascript
深入浅析golang zap 日志库使用(含文件切割、分级别存储和全局使用等)
2020/02/19 Javascript
tracking.js实现前端人脸识别功能
2020/04/16 Javascript
Python写的一个简单DNS服务器实例
2014/06/04 Python
django实现用户注册实例讲解
2019/10/30 Python
Python接口测试文件上传实例解析
2020/05/22 Python
深入理解css属性的选择对动画性能的影响
2016/04/20 HTML / CSS
使用html5制作loading图的示例
2014/04/14 HTML / CSS
英国图书音像网站:Hive.co.uk(图书、电子书、DVD、蓝光、音乐CD等)
2017/10/16 全球购物
Daisy London官网:英国最大的首饰集团IBB旗下
2019/02/28 全球购物
西安众合通用.net笔试题
2013/03/18 面试题
心理健康心得体会
2014/01/02 职场文书
2014领导班子四风问题查摆思想汇报
2014/09/13 职场文书
收费员岗位职责
2015/02/14 职场文书
幼儿园小班班务总结
2015/08/03 职场文书
建国70周年的心得体会(2篇)
2019/09/20 职场文书
Python编解码问题及文本文件处理方法详解
2021/06/20 Python
Apache Hudi 加速传统的批处理模式
2022/04/24 Servers