您的位置:首页 > Web前端 > JavaScript

关于ajaxfileupload.js一些问题和上传图片就立即显示图片功能

2015-11-04 15:27 896 查看
  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中已经有了立即显示的代码

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

所有这些我只是写出来解决的方法,但是具体的原理还不是很懂。欢迎大家吐槽和评论!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: