ajaxfileupload.js是上传文件的一个插件,最近碰到的一个问题是在谷歌浏览器上传文件之后,原文本框中的文件名称消失,网上搜了好长时间也没有十分满意的答案。无刷新上传文件我想到的只有ajax,ajaxfileupload.js插件非常简单,看个简单例子就会使用,不用明白js里面写的到底是什么。流程就是就是先利用jQuery的选择器获得file文件上传框中的文件路径值,然后js就会动态的创建一个iframe和表单,并在里面建立一个新的file 文件框,提供post方式提交到后台。最后,返回结果到前台。

  我的功能需求是在选中图片的时候就自动上传图片,并且可以马上显示,刚做的时候没有想到上传图片,用了一个onchange函数可以让上传的图片显示出来,之后提交之前有一个预览功能,之前的上传的图片还要展现出来,这个时候才想起来把图片先存放某一个地方,这样连上传即展现的功能也能解决。不过为了以后会用到这个功能我就和上传图片的一起写出来。

html上传文件的

 <script type="text/javascript" src='/Public/js/jquery-1.4.2.min.js'></script>
<!--上传图片的JS 修改之后的-->
<script charset="utf-8" src="/Public/js/ajaxfileupload_modify.js"></script>
<script type="text/javascript">
//图片展示和删除 其他函数是选中图片下面就会展现出来图片的相关函数
function onUploadImgChange(sender,img,obj){
if( !sender.value.match( /.jpg|.gif|.png|.bmp|.jpeg/i ) ){
alert('图片格式无效!');
return false;
}
var objPreview = document.getElementById(obj);
var file=document.getElementById(img);
if( sender.files && sender.files[0] ){
objPreview.style.display = 'block';
objPreview.style.width = 'auto';
objPreview.style.height = 'auto';
objPreview.src = window.URL.createObjectURL(file.files[0]);
}
//上传到服务器图片方便预览 这一块是选中图片即上传
$.ajaxFileUpload ({
url:'__URL__/page_preview', //你处理上传文件的服务端
secureuri:false, //与页面处理代码中file相对应的ID值
fileElementId:'btn_pic',
dataType: 'json', //返回数据类型:text,xml,json,html,scritp,jsonp五种
success: function (data)
{
if(data.file_infor ==1 )
{
//存放的地址展示出来
$("#tmp_btn_pic").val(data.file_url);
}
}
})
} function onPreviewLoad(sender){
autoSizePreview( sender, sender.offsetWidth, sender.offsetHeight );
} function autoSizePreview( objPre, originalWidth, originalHeight ){
var zoomParam = clacImgZoomParam( 300, 300, originalWidth, originalHeight );
objPre.style.width = zoomParam.width + 'px';
objPre.style.height = zoomParam.height + 'px';
objPre.style.marginTop = zoomParam.top + 'px';
objPre.style.marginLeft = zoomParam.left + 'px';
} function clacImgZoomParam( maxWidth, maxHeight, width, height ){
var param = { width:width, height:height, top:0, left:0 };
if( width>maxWidth || height>maxHeight ){
rateWidth = width / maxWidth;
rateHeight = height / maxHeight;
if( rateWidth > rateHeight ){
param.width = maxWidth;
param.height = height / rateWidth;
}else{
param.width = width / rateHeight;
param.height = maxHeight;
}
}
param.left = (maxWidth - param.width) / 2;
param.top = (maxHeight - param.height) / 2;
return param;
} function del_img(obj,div){
if(confirm("确定要删除此图片?"))
{
$('#'+obj+'').val('');
objPreview = document.getElementById(div);
objPreview.style.display = 'none';
}else{
return false;
}
}
</script>
<input type="file" name="btn_pic" id="btn_pic" onchange="onUploadImgChange(this,'btn_pic','preview2');" />
<div>
<img id="preview2" onload="onPreviewLoad(this)"/>
</div>
<input type="button" value="删除" onclick="del_img('btn_pic','preview2');" />

php后台处理

 function page_preview()
{//出来ajaxupload的图片
//如果有按钮图片先存放某个地方
$folder = "/img/" . date("Ym/d/");
$this->mkDirs(UPLOAD_PATH . $folder);
$path = $folder . time() . rand(1000,9999) . $_FILES['btn_pic']['name'];
$img_path = UPLOAD_PATH . $path;
$ok=@move_uploaded_file($_FILES['btn_pic']['tmp_name'],$img_path);
if($ok === FALSE)
{
$file_infor = 0;
echo '{"file_infor":"' . $file_infor .'"}';
}else
{
$file_infor = 1;
echo '{"file_infor":"' . $file_infor . '","file_url":"' . $path . '"}';
}
}

 在原来的ajaxfileupload.js中修改了一下就可以传完之后原来的文本框的值不会丢失。这也是从网上搜集来的我总结一下

jQuery.extend({

    createUploadIframe: function(id, uri)
{
//create frame
var frameId = 'jUploadFrame' + id; if(window.ActiveXObject) {
if(jQuery.browser.version=="9.0" || jQuery.browser.version=="10.0"){
var io = document.createElement('iframe');
io.id = frameId;
io.name = frameId;
}else if(jQuery.browser.version=="6.0" || jQuery.browser.version=="7.0" || jQuery.browser.version=="8.0"){
var io = document.createElement('<iframe id="' + frameId + '" name="' + frameId + '" />');
if(typeof uri== 'boolean'){
io.src = 'javascript:false';
}
else if(typeof uri== 'string'){
io.src = uri;
}
}
} else {
var io = document.createElement('iframe');
io.id = frameId;
io.name = frameId;
}
io.style.position = 'absolute';
io.style.top = '-1000px';
io.style.left = '-1000px'; document.body.appendChild(io); return io
},
createUploadForm: function(id, fileElementId)
{
//create form
var formId = 'jUploadForm' + id;
var fileId = 'jUploadFile' + id;
var form = $('<form action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>');
var oldElement = $('#' + fileElementId);
var newElement = $(oldElement).clone();
$(oldElement).attr('id', fileId);
$(oldElement).before(newElement);
$(oldElement).appendTo(form);
//set attributes
$(form).css('position', 'absolute');
$(form).css('top', '-1200px');
$(form).css('left', '-1200px');
$(form).appendTo('body');
return form;
}, ajaxFileUpload: function(s) {
// TODO introduce global settings, allowing the client to modify them for all requests, not only timeout
s = jQuery.extend({}, jQuery.ajaxSettings, s);
var id = s.fileElementId;
var form = jQuery.createUploadForm(id, s.fileElementId);
var io = jQuery.createUploadIframe(id, s.secureuri);
var frameId = 'jUploadFrame' + id;
var formId = 'jUploadForm' + id; // Watch for a new set of requests
if (s.global && ! jQuery.active++)
{
jQuery.event.trigger("ajaxStart");
} var requestDone = false;
// Create the request object
var xml = {}
if ( s.global )
jQuery.event.trigger("ajaxSend", [xml, s]);
// Wait for a response to come back var uploadCallback = function(isTimeout)
{
var io = document.getElementById(frameId);
try
{
if(io.contentWindow)
{
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)
{
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")
{
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);
// 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(); setTimeout(function()
{ try
{
$(io).remove();
                          //修改的
var fileElementId = 'jUploadFile' + id;
var oldElement = $('#' + fileElementId);
var newElement = $('#' + id);
$(newElement).after(oldElement);
$(newElement).remove();
$(oldElement).attr('id', id);
                          //结束
$(form).remove(); } 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 io = $('#' + frameId);
var form = $('#' + formId);
$(form).attr('action', s.url);
$(form).attr('method', 'POST');
$(form).attr('target', frameId);
if(form.encoding)
{
form.encoding = 'multipart/form-data';
}
else
{
form.enctype = 'multipart/form-data';
}
$(form).submit(); } catch(e)
{
jQuery.handleError(s, xml, null, e);
}
if(window.attachEvent){
document.getElementById(frameId).attachEvent('onload', uploadCallback);
}
else{
document.getElementById(frameId).addEventListener('load', uploadCallback, false);
}
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();
//alert($('param', data).each(function(){alert($(this).attr('value'));}));
return data;
}
})

这样就解决了ajax上传之后 原本文本框丢失的问题。

图片上传就显示,我们需要了解Javascript里File对象、Blob对象和window.URL.createObjectURL()方法。上面所写的html中已经有了立即显示的代码

以后可以研究研究其中的机制。

所有这些我只是写出来解决的方法,但是具体的原理还不是很懂。欢迎大家吐槽和评论!

关于ajaxfileupload.js一些问题和上传图片就立即显示图片功能的更多相关文章

  1. JS控制文本框中的密码显示/隐藏功能

    <html> <head> <title>[荐]JS控制文本框中的密码显示/隐藏功能_网页代码站(www.6a8a.com)</title> <s ...

  2. PHP JS JQ 异步上传并立即显示图片

    提交页面: <! DOCTYPE html> < html> < head> < meta charset ="GB2312" > ...

  3. SpringMVC结合ajaxfileupload.js实现文件无刷新上传

    直接看代码吧,注释都在里面 首先是web.xml <?xml version="1.0" encoding="UTF-8"?> <web-ap ...

  4. 通过修改ajaxFileUpload.js实现多图片动态上传并实现预览

    参考:http://smotive.iteye.com/blog/1903606 大部分我也是根据他的方法修改的,我也要根据name实现动态的多文件上传功能,但是有个问题使我一直无法实现多文件上传. ...

  5. 异常-----springmvc + ajaxfileupload解决ajax不能异步上传图片的问题。java.lang.ClassCastException: org.apache.catalina.connector.RequestFacade cannot be cast to org.springframework.web.multipart.

    说明这个问题产生的原因主要是form表单上传图片的时候必须是Content-Type:"multipart/form-data,这种格式的,但是ajax在页面不刷新的情况下去加载的时候只会把 ...

  6. jQuery插件之ajaxFileUpload(异步上传图片并实时显示,并解决onchange后ajaxFileUpload失效问题)

    参考学习: 第一篇:http://www.cnblogs.com/kissdodog/archive/2012/12/15/2819025.html 第二篇:http://www.jb51.net/a ...

  7. ASP.NET 使用ajaxfileupload.js插件出现上传较大文件失败的解决方法(ajaxfileupload.js第一弹)

    在写这篇的时候本来想把标题直接写成报错的提示,如下: “SecurityError:Blocked a frame with origin "http://localhost:55080&q ...

  8. ajaxfileupload.js异步上传

    转载:https://www.cnblogs.com/labimeilexin/p/6742647.html jQuery插件之ajaxFileUpload     ajaxFileUpload.js ...

  9. springmvc_ajax异步上传文件(基于ajaxfileupload.js)

    引入js <script th:src="@{/js/ajaxfileupload.js}"></script> html <tr> <t ...

随机推荐

  1. SolrCloud阶段总结

    http://www.cnblogs.com/guozk/p/3498844.html SolrCloud阶段总结 开发类型 全文检索相关开发 Solr版本 4.2 文件内容 本文介绍SolrClou ...

  2. 与QString("我是中文")完全一样,你必须告诉tr这个窄字符串是何种编码?你不告诉它,它就用latin1。于是所谓的乱码问题就出来了。

    在论坛中漂,经常遇到有人遇到tr相关的问题.用tr的有两类人: (1)因为发现中文老出问题,然后搜索,发现很多人用tr,于是他也开始用tr (2)另一类人,确实是出于国际化的需要,将需要在界面上显示的 ...

  3. Installing vSphere SDK for Perl

    Installing vSphere SDK for Perl 你可以安装vSphere SDK 在Linux 或者Microsoft Windows 系统,或者 部署 VSphere Managem ...

  4. .net framework client profile

    .NET Framework Client Profile The .NET Client Profile is a subset of the .NET Framework, which was p ...

  5. 可恶的0x1A

    很少用fread读文件,今天用fread读一个文件死活缺一点,折腾半天才发现原来遇到0x1a. 0x1a 是 Ctrl+Z ,是模拟文件结束的符号,就是文件遇到0x1a后,认为文件已经结束. 哎!记下

  6. uC/OS-II学习历程(持续更新)

    开始接触嵌入式操作系统的知识了,作为入门,选择了一个小巧的系统——uC/OS-II.当然,难度也并不小,至少对我来说是这样.刚刚开始看,使用的参考书是任哲的<嵌入式实时操作系统uC/OS-II原 ...

  7. 怎么样把UIImage保存到相册

    需要保存的图片放在UIImage里面,保存只需要运行一下代码:     UIImageWriteToSavedPhotosAlbum(outputImage, nil, nil, nil);

  8. FIREDAC TFDCONNECTION连接MYSQL数据库

    FIREDAC TFDCONNECTION连接MYSQL数据库 procedure TfrmDB.ConnectDB;begin FDMoniFlatFileClientLink1.FileName ...

  9. tableview: 实现tableview 的 section header 跟随tableview滑动

    方法一:(只有一个headerView)一段 如果你的tableview恰好只有一个headerView,实现这种效果就好办了.把要设置的headerView设置成tableView的header而不 ...

  10. 【Android - V】之Toolbar的使用

    Toolbar是Android V7包中的一个控件,用来代替Action Bar作为界面的头部标题栏布局.Toolbar相对于Action Bar的特点是更加灵活,可以显示在任何位置. 首先先来看To ...