js上传文件
一、原始的XMLHttpRequestjs上传文件过程(參考地址:http://blog.sina.com.cn/s/blog_5d64f7e3010127ns.html)
用到两个对象
第一个对象:FormData
第二个对象:XMLHttpRequest
眼下新版的Firefox 与 Chrome 等支持HTML5的浏览器完美的支持这两个对象,但IE9尚未支持 FormData 对象。还在用IE6 ? 仅仅能仰天长叹....
有了这两个对象。我们能够真正的实现Ajax方式上传文件。
演示样例代码:
<!DOCTYPE html>
<html>
<head>
<title>Html5 Ajax 上传文件</title>
<script type="text/javascript">
function UpladFile() {
var fileObj = document.getElementByIdx_x_x("file").files[0]; // 获取文件对象
var FileController = "../file/save"; // 接收上传文件的后台地址
// FormData 对象
var form = new FormData();
form.append("author", "hooyes"); // 能够添加表单数据
form.append("file", fileObj); // 文件对象
// XMLHttpRequest 对象
var xhr = new XMLHttpRequest();
xhr.open("post", FileController, true);
xhr.onload = function () {
alert("上传完毕!");
};
xhr.send(form);
}
</script>
</head>
<body>
<input type="file" id="file" name="img1" />
<input type="button" onclick="UpladFile()" value="上传" />
</body>
</html>
java 代码:
private File img1;
private String img1FileName;
private String img1ContentType;
private String saveFile() {
int lastDotIndex = img1FileName.lastIndexOf(".");
String imgType = img1FileName.substring(lastDotIndex - 1, img1FileName.length());
String tempName = UploadImgTempFilePath.getUploadFilePath() + UUID.randomUUID() + imgType;
try {
// 建立文件输出流
FileOutputStream fos = new FileOutputStream(tempName);
// 建立文件上传流
FileInputStream fis = new FileInputStream(img1);
byte[] buffer = new byte[1024];
int len = 0;
while ((len = fis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
fis.close();
fos.close();
} catch (Exception e) {
return null;
}
return tempName;
}
二、 使用ajax的插件ajaxfileupload(參考地址:http://www.cnblogs.com/linjiqin/p/3530848.html)
引入js:
<script type="text/javascript" src="<%=basePath%>resources/js/jquery-1.2.1.js"></script>
<script type="text/javascript" src="<%=basePath%>resources/js/ajaxfileupload.js"></script>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ include file="/base.jsp" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>ajax文件上传</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<link rel="stylesheet" type="text/css" href="validate/ajaxfileupload.css" />
<script type="text/javascript" src="validate/jquery-1.6.2.min.js"></script>
<script type="text/javascript" src="validate/ajaxfileupload.js" ></script>
<script type="text/javascript">
$(function(){
//上传图片
$("#btnUpload").click(function() {
alert(ajaxFileUpload());
});
});
function ajaxFileUpload() {
// 開始上传文件时显示一个图片
$("#wait_loading").ajaxStart(function() {
$(this).show();
// 文件上传完毕将图片隐藏起来
}).ajaxComplete(function() {
$(this).hide();
});
var elementIds=["flag"]; //flag为id、name属性名
$.ajaxFileUpload({
url: 'uploadAjax.htm',
type: 'post',
secureuri: false, //一般设置为false
fileElementId: 'file', // 上传文件的id、name属性名
dataType: 'text', //返回值类型。一般设置为json、application/json
elementIds: elementIds, //传递參数到server
success: function(data, status){
alert(data);
},
error: function(data, status, e){
alert(e);
}
});
//return false;
}
</script>
</head>
<body>
<div id="wait_loading" style="padding: 50px 0 0 0;display:none;">
<div style="width: 103px;margin: 0 auto;"><img src="<%=path %>/images/loading.gif"/></div>
<br></br>
<div style="width: 103px;margin: 0 auto;"><span>请稍等...</span></div>
<br></br>
</div>
<input type="file" id="file" name="file"><br/>
<input type="hidden" id="flag" name="flag" value="ajax文件上传"/>
<input type="button" id="btnUpload" value="上传图片" />
</body>
</html>
后台java代码类似。
三、ajaxfileupload源代码分析(參考地址:http://blog.csdn.net/it_man/article/details/43800957)
jQuery.extend({
createUploadIframe: function (id, uri) {//id为当前系统时间字符串。uri是外部传入的json对象的一个參数
//create frame
var frameId = 'jUploadFrame' + id; //给iframe加入一个独一无二的id
var iframeHtml = '<iframe id="' + frameId + '" name="' + frameId + '" style="position:absolute; top:-9999px; left:-9999px"'; //创建iframe元素
if (window.ActiveXObject) {//推断浏览器是否支持ActiveX控件
if (typeof uri == 'boolean') {
iframeHtml += ' src="' + 'javascript:false' + '"';
} else if (typeof uri == 'string') {
iframeHtml += ' src="' + uri + '"';
}
}
iframeHtml += ' />';
jQuery(iframeHtml).appendTo(document.body); //将动态iframe追加到body中
return jQuery('#' + frameId).get(0); //返回iframe对象
},
createUploadForm: function (id, fileElementId, data) {//id为当前系统时间字符串,fileElementId为页面<input type='file' />的id。data的值须要依据传入json的键来决定
//create form
var formId = 'jUploadForm' + id; //给form加入一个独一无二的id
var fileId = 'jUploadFile' + id; //给<input type='file' />加入一个独一无二的id
var form = jQuery('<form action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data" ></form>'); //创建form元素
if (data) {//通常为false
for (var i in data) {
jQuery('<input type="hidden" name="' + i + '" value="' + data[i] + '" />').appendTo(form); //依据data的内容。创建隐藏域,这部分我还不知道是什么时候用到。预计是传入json的时候,假设默认传一些參数的话要用到。
}
} var oldElement = jQuery('#' + fileElementId); //得到页面中的<input type='file' />对象
var newElement = jQuery(oldElement).clone(); //克隆页面中的<input type='file' />对象
jQuery(oldElement).attr('id', fileId); //改动原对象的id
jQuery(oldElement).before(newElement); //在原对象前插入克隆对象
jQuery(oldElement).appendTo(form); //把原对象插入到动态form的结尾处
//set attributes
jQuery(form).css('position', 'absolute'); //给动态form加入样式,使其浮动起来,
jQuery(form).css('top', '-1200px');
jQuery(form).css('left', '-1200px');
jQuery(form).appendTo('body'); //把动态form插入到body中
return form;
},
ajaxFileUpload: function (s) {//这里s是个json对象。传入一些ajax的參数
// TODO introduce global settings, allowing the client to modify them for all requests, not only timeout
s = jQuery.extend({}, jQuery.ajaxSettings, s); //此时的s对象是由jQuery.ajaxSettings和原s对象扩展后的对象
var id = new Date().getTime(); //取当前系统时间,目的是得到一个独一无二的数字
var form = jQuery.createUploadForm(id, s.fileElementId, (typeof (s.data) == 'undefined' ? false : s.data)); //创建动态form
var io = jQuery.createUploadIframe(id, s.secureuri); //创建动态iframe
var frameId = 'jUploadFrame' + id; //动态iframe的id
var formId = 'jUploadForm' + id; //动态form的id
// Watch for a new set of requests
if (s.global && !jQuery.active++) {//当jQuery開始一个ajax请求时发生
jQuery.event.trigger("ajaxStart"); //触发ajaxStart方法
} var requestDone = false; //请求完毕标志
// Create the request object
var xml = {}; if (s.global)
jQuery.event.trigger("ajaxSend", [xml, s]); //触发ajaxSend方法
// Wait for a response to come back
var uploadCallback = function (isTimeout) {//回调函数
var io = document.getElementById(frameId); //得到iframe对象
try { if (io.contentWindow) {//动态iframe所在窗体对象是否存在
xml.responseText = io.contentWindow.document.body ?
io.contentWindow.document.body.innerHTML : null;
xml.responseXML = io.contentWindow.document.XMLDocument ? io.contentWindow.document.XMLDocument : io.contentWindow.document;
} else if (io.contentDocument) {//动态iframe的文档对象是否存在
xml.responseText = io.contentDocument.document.body ? io.contentDocument.document.body.innerHTML : null;
xml.responseXML = io.contentDocument.document.XMLDocument ?
io.contentDocument.document.XMLDocument : io.contentDocument.document;
}
} catch (e) {
jQuery.handleError(s, xml, null, e);
} if (xml || isTimeout == "timeout") {//xml变量被赋值或者isTimeout == "timeout"都表示请求发出,而且有响应
requestDone = true; //请求完毕
var status; try {
status = isTimeout != "timeout" ? "success" : "error"; //假设不是“超时”。表示请求成功
// Make sure that the request was successful or notmodified
if (status != "error") { // process the data (runs the xml through httpData regardless of callback)
var data = jQuery.uploadHttpData(xml, s.dataType); //依据传送的type类型,返回json对象,此时返回的data就是后台操作后的返回结果
// If a local callback was specified, fire it and pass it the data
if (s.success)
s.success(data, status); //运行上传成功的操作
// Fire the global callback
if (s.global)
jQuery.event.trigger("ajaxSuccess", [xml, s]);
} else
jQuery.handleError(s, xml, status);
} catch (e) {
status = "error";
jQuery.handleError(s, xml, status, e);
} // The request was completed
if (s.global)
jQuery.event.trigger("ajaxComplete", [xml, s]); // Handle the global AJAX counter
if (s.global && ! --jQuery.active)
jQuery.event.trigger("ajaxStop"); // Process result
if (s.complete)
s.complete(xml, status);
jQuery(io).unbind();//移除iframe的事件处理程序
setTimeout(function () {//设置超时时间
try {
jQuery(io).remove();//移除动态iframe
jQuery(form).remove();//移除动态form
} catch (e) {
jQuery.handleError(s, xml, null, e);
}
}, 100)
xml = null
}
} // Timeout checker
if (s.timeout > 0) {//超时检測
setTimeout(function () { // Check to see if the request is still happening
if (!requestDone) uploadCallback("timeout");//假设请求仍未完毕。就发送超时信号
}, s.timeout);
} try { var form = jQuery('#' + formId);
jQuery(form).attr('action', s.url);//传入的ajax页面导向url
jQuery(form).attr('method', 'POST');//设置提交表单方式
jQuery(form).attr('target', frameId);//返回的目标iframe。就是创建的动态iframe
if (form.encoding) {//选择编码方式
jQuery(form).attr('encoding', 'multipart/form-data');
} else {
jQuery(form).attr('enctype', 'multipart/form-data');
}
jQuery(form).submit();//提交form表单
} catch (e) {
jQuery.handleError(s, xml, null, e);
}
jQuery('#' + frameId).load(uploadCallback); //ajax 请求从server载入数据。同一时候传入回调函数
return { abort: function () { } };
},
uploadHttpData: function (r, type) { var data = !type;
data = type == "xml" || data ? r.responseXML : r.responseText; // If the type is "script", eval it in global context
if (type == "script")
jQuery.globalEval(data); // Get the JavaScript object, if JSON is used.
if (type == "json")
eval("data = " + data); // evaluate scripts within html
if (type == "html")
jQuery("<div>").html(data).evalScripts(); return data;
}
})
结论:
查看ajax的方式也是通过构建type=file的方式,用form上传的。所以假设能通过form方式提交的话,就通过form提交吧。
别人的使用实例,比較好:http://www.cnblogs.com/kissdodog/archive/2012/12/15/2819025.html
js上传文件的更多相关文章
- 使用ajaxfileupload.js上传文件
一直以来上传文件都是使用form表单上传文件,也看到过有人使用js上传文件,不过看起来蛮简单的也就没有怎么去理会.今天突然要使用这种方式上传文件,期间还遇到点问题.因此就记录下来,方便以后遇到这样的问 ...
- js 上传文件后缀名的判断 var flag=false;应用
js 上传文件后缀名的判断 var flag=false;应用 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional// ...
- js上传文件带参数,并且,返回给前台文件路径,解析上传的xml文件,存储到数据库中
ajaxfileupload.js jQuery.extend({ createUploadIframe: function(id, uri) { //create frame var frameId ...
- atitit.javascript js 上传文件的本地预览
atitit.javascript js 上传文件的本地预览 1. .URL.createObjectURL 1 1.1. 吊销所有使用 URL.createObjectURL 而创建的 URL,以 ...
- 前端js上传文件 到后端接收文件
下面是前端js代码: <html> <head> <meta http-equiv="Content-Type" content="text ...
- 纯js上传文件 很好用
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name ...
- 原生js上传文件,使用new FormData()
当创建一个内容较多的表单,表单里面又有了文件上传,文件上传也需要表单提交,单一的上传文件很好操作: <form action="接口" enctype="multi ...
- django + dropzone.js 上传文件
1.dropzone.js http://www.dropzonejs.com/ dropzone.js是一个可预览\可定制化的文件拖拽上传,实现AJAX异步上传文件的工具 2.dropzone.js ...
- js上传文件获取文件流
上传文件获取文件流 <div> 上传文件 : <input type="file" name = "file" id = "file ...
随机推荐
- 微信小程序一些常见的坑
1.小程序都报wxss编译错误 解决方法: 在控制台输入openVendor() ,清除里面的wcsc wcsc.exe 然后重启工具 2.微信小程序wx:for警告 Now you can prov ...
- 解决opencv在pycharm中无代码自动提示的bug
2018-03-0422:19:39 首先,估计这不是bug 可能是我自己误操作导致的,但是让我搞了好久才搞定,实在是苦恼 如图已实现功能,百度里有很多朋友出现了,这个无代码提示的问题 大概是这样的, ...
- 关于使用Axis2 webservice 处理Fault响应时抛org.apache.axis2.AxisFault的分析
使用Axis2这个框架进行webservice协议通讯,期间出了个问题,我(CLIENT)请求后,当服务端返回符合协议的SOAP异常报文,例如<soap:fault> ... 我的程序直接 ...
- spring加载classpath与classpath*的区别别
1.无论是classpath还是classpath*都可以加载整个classpath下(包括jar包里面)的资源文件. 2.classpath只会返回第一个匹配的资源,查找路径是优先在项目中存在资源文 ...
- Linux 压力测试及内存检测
常用的 Stress / Performance 工具 http://benjr.tw/532 Linux中的常用内存问题检测工具 https://blog.csdn.net/jinzhuojun/a ...
- java继承问题
代码: 父类: public class Father { public Father() { System.out.println("基类构造函数{"); show(); new ...
- HDU_1864_最大报销额_01背包
最大报销额 Time Limit:1000MS Memory Limit:32768KB 64bit IO Format:%I64d & %I64u Submit Status ...
- Understanding and Analyzing Application Crash Reports
Introduction When an application crashes, a crash report is created and stored on the device. Crash ...
- [USACO] 奶牛混合起来 Mixed Up Cows
题目描述 Each of Farmer John's N (4 <= N <= 16) cows has a unique serial number S_i (1 <= S_i & ...
- <MyBatis>入门一 HelloWorld
1.HelloWorld 导入依赖 <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis --> <dependen ...