html5+java 文件异步读取及上传关键代码段

功能:

1.多文件文件拖拽上传,file input 多文件选择

2.html5 File Api 异步FormData,blob上传,图片显示

3.java端接受

核心代码:

1.拖拽代码段:

 <div id="dropzone">
<div>Drag & drop your file here...</div>
<div id='showFile'></div>
<div style='clear: both'></div>
</div> <script>
/*function for drag and drop*/
window.onload = function() {
var dropzone = document.getElementById("dropzone");
dropzone.ondragover = dropzone.ondragenter = function(event) {
event.preventDefault();
event.stopPropagation();
}
dropzone.ondrop = function(event) {
event.preventDefault();
var filesArray = event.dataTransfer.files;
for ( var i = 0; i < filesArray.length; i++) {
var fObj = new fileObj(filesArray[i], idTmp);
// to do tasks with dropData
}
event.stopPropagation();
}
}
</script>

file input 多文件选择:

 <p>
Upload File: <input id='uploadFile' type="file" name="file" multiple />
</p> <script>
$("#uploadFile").change(function(e) {
event.preventDefault();
var filesArray = e.target.files;
for ( var i = 0; i < filesArray.length; i++) {
var fObj = new fileObj(filesArray[i], idTmp);
// to do tasks with dropData
idTmp++;
}
event.stopPropagation();
});
</script>

2.html5 File Api 异步上传:

1).使用FormData上传

 <!DOCTYPE html>
<html>
<head>
<title>Upload Files using XMLHttpRequest - Minimal</title> <script type="text/javascript">
function fileSelected() {
var file = document.getElementById('fileToUpload').files[0];
if (file) {
var fileSize = 0;
if (file.size > 1024 * 1024)
fileSize = (Math.round(file.size * 100 / (1024 * 1024)) / 100).toString() + 'MB';
else
fileSize = (Math.round(file.size * 100 / 1024) / 100).toString() + 'KB'; document.getElementById('fileName').innerHTML = 'Name: ' + file.name;
document.getElementById('fileSize').innerHTML = 'Size: ' + fileSize;
document.getElementById('fileType').innerHTML = 'Type: ' + file.type;
}
} function uploadFile() {
var fd = new FormData();
fd.append("fileToUpload", document.getElementById('fileToUpload').files[0]);
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener("progress", uploadProgress, false);
xhr.addEventListener("load", uploadComplete, false);
xhr.addEventListener("error", uploadFailed, false);
xhr.addEventListener("abort", uploadCanceled, false);
xhr.open("POST", "UploadMinimal.aspx");
xhr.send(fd);
} function uploadProgress(evt) {
if (evt.lengthComputable) {
var percentComplete = Math.round(evt.loaded * 100 / evt.total);
document.getElementById('progressNumber').innerHTML = percentComplete.toString() + '%';
}
else {
document.getElementById('progressNumber').innerHTML = 'unable to compute';
}
} function uploadComplete(evt) {
/* This event is raised when the server send back a response */
alert(evt.target.responseText);
} function uploadFailed(evt) {
alert("There was an error attempting to upload the file.");
} function uploadCanceled(evt) {
alert("The upload has been canceled by the user or the browser dropped the connection.");
}
</script>
</head>
<body>
<form id="form1" enctype="multipart/form-data" method="post" action="upload.php">
<div class="row">
<label for="fileToUpload">Select a File to Upload</label>
<input type="file" name="fileToUpload" id="fileToUpload" onchange="fileSelected();"/>
</div>
<div id="fileName"></div>
<div id="fileSize"></div>
<div id="fileType"></div>
<div class="row">
<input type="button" onclick="uploadFile()" value="Upload" />
</div>
<div id="progressNumber"></div>
</form> </body>
</html>

2).使用blob,readAsBinaryString上传

 <!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>HTML5 File Upload[By WangXinsheng]</title>
<script src="../js/jquery-1.11.1.min.js"></script>
</head>
<style>
#dropzone {
margin-top: 10px;
width: 500px;
min-height: 300px;
height: 100%;
border: 1px dotted grey;
} header {
font-weight: bold;
} .uploadFile {
display: inline;
float: left;
width: 45%;
border: 1px solid gray;
margin: 5px;
min-height: 20px;
padding-bottom: 5px;
padding-left: 5px;
} .uploadFile p {
margin: 2px;
} .uploadFile progress {
-webkit-appearance: none;
}
.uploadFile .ok{
cursor:pointer;
} .uploadFile ::-webkit-progress-inner-element { } .uploadFile ::-webkit-progress-bar {
background: white;
border: 1px solid gray;
} .uploadFile ::-webkit-progress-value {
background: green;
} .uploadFile ::-moz-progress-bar {
background: white
} .uploadFile ::-ms-fill {
background: green;
}
</style>
<body>
<header>HTML5 File Upload</header>
<p>
Upload File: <input id='uploadFile' type="file" name="file" multiple />
</p> <div id="dropzone">
<div>Drag & drop your file here...</div>
<div id='showFile'></div>
<div style='clear: both'></div>
</div>
<script>
var oneFileDom = "<div class='uploadFile' id='uf_{%id%}'>"
+"<p>{%name%}</p>"
+"<progress width='100%'></progress>"
+"<span class='ok' style='display:none;padding-left:10px;color:green;font-weight:bold__:bold;'>转换</span>"
+"</div>";
var idTmp = 0;
/*all file obj list*/
var fileObjLst = [];
/*file object*/
var fileObj = function(file, id) {
this.fileName;
this.file = file;
this.uploadSize = 0;
this.finishFlg = false;
this.sliceStart = 0;
this.maxPiece = 0;
this.blockCount = 0;
this.blockCur = 0;
this.reader = null;
this.dom;
this.id = id;
this.xhr;
}
fileObj.prototype.init = function() {
var tmpPiece = Math.ceil(this.file.size * 0.5);
this.maxPiece = tmpPiece > 1024 * 1024 * 0.2 ? 1024 * 1024 * 0.2
: (tmpPiece < 1024 * 1024 * 0.1 ? 1024 * 1024 *0.1: tmpPiece);
this.blockCount = Math.ceil(this.file.size / this.maxPiece);
this.sliceEnd = this.maxPiece;
this.fileName = new Date().getTime();
$("#showFile").prepend(
$(oneFileDom.replace('{%id%}', this.id).replace("{%name%}",
this.file.name)));
}
fileObj.prototype.send = function() {
console.log(this.id);
$("#uf_" + this.id).find("progress").attr("value", '0');
$("#uf_" + this.id).find("progress").attr("max",
this.file.size + ''); this.reader = new FileReader(); this.Bind(this.reader, "loadend", this.onloadend, this);
this.Bind(this.reader, "loadstart", this.onloadstart, this);
this.Bind(this.reader, "progress", this.onprogress, this);
this.Bind(this.reader, "load", this.onload, this); var blob, file = this.file;
console.log(file);
try {
blob = sliceBlob(file, this.sliceStart, this.sliceStart
+ this.maxPiece + 1);
} catch (e) {
console.log("error:" + e);
}
this.sliceStart = this.sliceStart + this.maxPiece + 1;
this.reader.readAsBinaryString(blob);
}
fileObj.prototype.onload = function() {
// 这个事件在读取成功结束后触发
console.log("load complete");
}
fileObj.prototype.onloadstart = function() {
// 这个事件在读取开始时触发
console.log("onloadstart");
//document.getElementById("bytesTotal").innerHTML = file.size;
}
fileObj.prototype.onprogress = function(p) {
// 这个事件在读取进行中定时触发
console.log("onprogress");
//document.getElementById("bytesRead").textContent = p.loaded;
}
fileObj.prototype.onloadend = function() {
// 这个事件在读取结束后,无论成功或者失败都会触发
//console.log(this.id);
if (this.reader.error) {
console.log(this.reader.error);
} else {
var url1 = "/ExcelToWord/morning?over=0&fileName=["
+ this.fileName + "]" + this.file.name, url2 = "/ExcelToWord/morning?over=1&fileName=["
+ this.fileName + "]" + this.file.name, url = url1;
this.blockCur++; this.uploadSize = ((this.sliceStart - 1) < this.file.size) ? (this.sliceStart - 1)
: this.file.size;
$("#uf_" + this.id).find("progress").attr("value",
this.uploadSize + '');
console.log(this.uploadSize, this.file.size);
if (this.blockCur > this.blockCount) {
//$("#uf_"+this.id).find(".ok").show();
console.log('over');
return;
} else if (this.blockCur == this.blockCount) {
// last piece
console.log('last');
url = url2;
}
console.log(this.blockCur, this.blockCount);
// 构造 XMLHttpRequest 对象,发送文件 Binary 数据
var me = this;
this.xhr = new XMLHttpRequest();
this.xhr.open("POST", url);
this.xhr.overrideMimeType("application/octet-stream");
this.xhr.sendAsBinary(this.reader.result);
this.Bind(this.xhr, "readystatechange",
this.onreadystatechange, this);
}
}
fileObj.prototype.onreadystatechange = function() {
var me = this;
if (this.xhr.readyState == 4) {
if (this.xhr.status == 200) {
console.log("upload complete");
console.log("response: " + this.xhr.responseText);
console.log("hello" + me.id);
var json = eval("(" + this.xhr.responseText + ")");
console.log(json.over);
if (json.over == "1") {
$("#uf_" + this.id).find(".ok").attr("serverName",
json.data);
$("#uf_" + this.id).find(".ok").show();
console.log('over');
return;
}
var blob, file = me.file;
try {
blob = sliceBlob(file, me.sliceStart, me.sliceStart
+ me.maxPiece + 1);
} catch (e) {
console.log("error:" + e);
}
me.sliceStart = me.sliceStart + me.maxPiece + 1;
me.reader.readAsBinaryString(blob);
}
}
}
fileObj.prototype.Bind = function(control, eventName, callBack, scope) {
if (!scope) {
scope = window;
}
$(control).bind(eventName, function() {
callBack.apply(scope, arguments);
});
}
function sliceBlob(blob, start, end, type) { type = type || blob.type; if (blob.mozSlice) {
return blob.mozSlice(start, end, type);
} else if (blob.webkitSlice) {
return blob.webkitSlice(start, end, type);
} else if (blob.slice) {
return blob.slice(start, end, type);
} else {
throw new Error("This doesn't work!");
}
}
/*function for drag and drop*/
window.onload = function() {
var dropzone = document.getElementById("dropzone");
dropzone.ondragover = dropzone.ondragenter = function(event) {
event.preventDefault();
event.stopPropagation();
}
dropzone.ondrop = function(event) {
event.preventDefault();
var filesArray = event.dataTransfer.files;
for ( var i = 0; i < filesArray.length; i++) {
var fObj = new fileObj(filesArray[i], idTmp);
fObj.init();
fObj.send(fObj);
fileObjLst.push(fObj);
idTmp++;
}
event.stopPropagation();
}
$("#uploadFile").change(function(e) {
event.preventDefault();
var filesArray = e.target.files;
for ( var i = 0; i < filesArray.length; i++) {
var fObj = new fileObj(filesArray[i], idTmp);
fObj.init();
fObj.send(fObj);
fileObjLst.push(fObj);
idTmp++;
}
event.stopPropagation();
});
} if (window.navigator.userAgent.toLowerCase().indexOf("chrome") > -1) {
XMLHttpRequest.prototype.sendAsBinary = function(datastr) {
function byteValue(x) {
return x.charCodeAt(0) & 0xff;
}
var ords = Array.prototype.map.call(datastr, byteValue);
var ui8a = new Uint8Array(ords);
this.send(ui8a.buffer);
}
}
</script>
</body>
</html>

3).Image 文件上传本地预览

 // 图片文件
var reader = new FileReader();
reader.readAsDataURL(imageFile);
// reader读取完成的回调,设置src属性,显示图片.
// 或者设置css的背景属性都可
reader.onload = function(e) {
document.getElementById('imageId').src = e.target.result;
}

3.java端接受

     @RequestMapping("/url")
@ResponseBody
public Map<String, Object> handleRequest(HttpServletRequest request,
HttpServletResponse response) throws Exception {
String fileName = request.getParameter("fileName");
fileName = new String(fileName.getBytes("ISO-8859-1"),"UTF-8");
String overFlg = request.getParameter("over"); // 0:go on;1:over
System.out.println("get: " + fileName);
byte[] buf = new byte[1024]; File file = new File(ExcelTmpPath + /*"[" + UUID.randomUUID().toString()
+ "]" +*/ fileName);
InputStream is = null;
BufferedOutputStream fileOut = new BufferedOutputStream(
new FileOutputStream(file, true));
try { is = request.getInputStream(); while (true) { int bytesIn = is.read(buf, 0, 1024);
System.out.println(bytesIn);
if (bytesIn == -1) {
break;
} else {
fileOut.write(buf, 0, bytesIn);
}
} fileOut.flush();
fileOut.close();
System.out.println(file.getAbsolutePath());
} catch (IOException e) {
System.out.println("error info");
}
Map<String, Object> map = new HashMap<String, Object>();
map.put("over", overFlg);
map.put("data", fileName);
return map;
}

[html5+java]文件异步读取及上传核心代码的更多相关文章

  1. ASP.NET MVC 使用Uploadify实现多文件异步无刷新上传

    软件技术开发,合作请联系QQ:858-048-581 这里我通过使用uploadify组件来实现异步无刷新多文件上传功能. 1.首先下载组件包uploadify,我这里使用的版本是3.1 2.下载后解 ...

  2. springmvc附件上传核心代码

    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.Comm ...

  3. Android中实现异步轮询上传文件

    前言 前段时间要求项目中需要实现一个刷卡考勤的功能,因为涉及到上传图片文件,为加快考勤的速度,封装了一个异步轮询上传文件的帮助类 效果  先上效果图 设计思路 数据库使用的框架是GreenDao,一个 ...

  4. Java模拟客户端向服务器上传文件

    先来了解一下客户端与服务器Tcp通信的基本步骤: 服务器端先启动,然后启动客户端向服务器端发送数据. 服务器端收到客户端发送的数据,服务器端会响应应客户端,向客户端发送响应结果. 客户端读取服务器发送 ...

  5. Java模拟表单POST上传文件

    JAVA模拟表单POST上传文件 import java.awt.image.BufferedImage;import java.awt.image.ColorModel;import java.io ...

  6. HTML5按比例缩略图片并上传的实例

    <!DOCTYPE HTML PUBLIC> <html> <head> <meta charset="utf-8"> <sc ...

  7. 求大师点化,寻求大文件(最大20G左右)上传方案

    之前仿造uploadify写了一个HTML5版的文件上传插件,没看过的朋友可以点此先看一下~得到了不少朋友的好评,我自己也用在了项目中,不论是用户头像上传,还是各种媒体文件的上传,以及各种个性的业务需 ...

  8. hTML5实现表单内的上传文件框,上传前预览图片,针刷新预览images

    hTML5实现表单内的上传文件框,上传前预览图片,针刷新预览images, 本例子主要是使用HTML5 的File API,建立一個可存取到该file的url, 一个空的img标签,ID为img0,把 ...

  9. PHP之文件的锁定、上传与下载

    小结文件的锁定机制.上传和下载 1.文件锁定 现在都在讲究什么分布式.并发等,实际上文件的操作也是并发的,在网络环境下,多个用户在同一时刻访问页面,对同一服务器上的同一文件进行着读取,如果,这个用户刚 ...

随机推荐

  1. python--爬虫入门(八)体验HTMLParser解析网页,网页抓取解析整合练习

    python系列均基于python3.4环境  基本概念 html.parser的核心是HTMLParser类.工作的流程是:当你feed给它一个类似HTML格式的字符串时,它会调用goahead方法 ...

  2. Spring MVC异常处理详解

    Spring MVC中异常处理的类体系结构 下图中,我画出了Spring MVC中,跟异常处理相关的主要类和接口. 在Spring MVC中,所有用于处理在请求映射和请求处理过程中抛出的异常的类,都要 ...

  3. 自制简单实用IoC

    IoC是个好东西,但是为了这个功能而使用类似 Castle 这种大型框架的话,感觉还是不大好 代码是之前写的,一直没详细搞,今天整理了一下,感觉挺实用的. IoC定义接口: using System; ...

  4. C# Socket系列三 socket通信的封包和拆包

    通过系列二 我们已经实现了socket的简单通信 接下来我们测试一下,在时间应用的场景下,我们会快速且大量的传输数据的情况! class Program { static void Main(stri ...

  5. SwiftLint——Swift代码检查及自动格式化工具

    某软不给力,正在做的UWP项目停工了.官方说法是要等到RS2发布新的VOIP架构,再看看是不是给某软面子.虽然Beta用户中发出了几点愤怒的声音,但是木有用.有用的只能是某软的Skype for bu ...

  6. 关于MYSQL数据库安装方式及相关设置简要说明

    网上关于MYSQL的教程非常多,但都不是最新的,我这里只是针对最新版本的MY SQL 的安装与设置进行一个简要的说明,大部份操作都相同. 以下是按照WINDOWS 64位操作系统+MY SQL 5.6 ...

  7. 使用MVVM-Sidekick开发Universal App(二)

    上一篇文章已经建立了基本的实体类,并且搞定了多语言的问题,以后在app里用字符串的时候就可以从资源文件中取了.现在继续进行. 一.添加一个页面 CurrencyExchanger首页是一个货币兑换的列 ...

  8. 温故而知新--sql存储过程复习

    存储过程是已编译好的T-SQL语句的集合,可以随时调用,速度快,不易出错. 可以传递参数,普通参数和输出参数(output) 实例1 create proc Newpro @testVarA int, ...

  9. c#使用WebClient登录网站抓取登录后的网页

    C#登录网站实际上就是模拟浏览器提交表单,然后记录浏览器响应返回的会话Cookie值,再次发送请求时带着这个会话cookie值去请求就可以实现模拟登录的效果了. 如下类CookieAwareWebCl ...

  10. 15天玩转redis —— 第五篇 集合对象类型

    这篇我们来看看Redis五大类型中的第四大类型:“集合类型”,集合类型还是蛮有意思的,第一个是因为它算是只使用key的Dictionary简易版, 这样说来的话,它就比Dictionary节省很多内存 ...