关于ajaxfileupload.js一些问题和上传图片就立即显示图片功能
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一些问题和上传图片就立即显示图片功能的更多相关文章
- JS控制文本框中的密码显示/隐藏功能
<html> <head> <title>[荐]JS控制文本框中的密码显示/隐藏功能_网页代码站(www.6a8a.com)</title> <s ...
- PHP JS JQ 异步上传并立即显示图片
提交页面: <! DOCTYPE html> < html> < head> < meta charset ="GB2312" > ...
- SpringMVC结合ajaxfileupload.js实现文件无刷新上传
直接看代码吧,注释都在里面 首先是web.xml <?xml version="1.0" encoding="UTF-8"?> <web-ap ...
- 通过修改ajaxFileUpload.js实现多图片动态上传并实现预览
参考:http://smotive.iteye.com/blog/1903606 大部分我也是根据他的方法修改的,我也要根据name实现动态的多文件上传功能,但是有个问题使我一直无法实现多文件上传. ...
- 异常-----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在页面不刷新的情况下去加载的时候只会把 ...
- jQuery插件之ajaxFileUpload(异步上传图片并实时显示,并解决onchange后ajaxFileUpload失效问题)
参考学习: 第一篇:http://www.cnblogs.com/kissdodog/archive/2012/12/15/2819025.html 第二篇:http://www.jb51.net/a ...
- ASP.NET 使用ajaxfileupload.js插件出现上传较大文件失败的解决方法(ajaxfileupload.js第一弹)
在写这篇的时候本来想把标题直接写成报错的提示,如下: “SecurityError:Blocked a frame with origin "http://localhost:55080&q ...
- ajaxfileupload.js异步上传
转载:https://www.cnblogs.com/labimeilexin/p/6742647.html jQuery插件之ajaxFileUpload ajaxFileUpload.js ...
- springmvc_ajax异步上传文件(基于ajaxfileupload.js)
引入js <script th:src="@{/js/ajaxfileupload.js}"></script> html <tr> <t ...
随机推荐
- IndexedDB demo showcase
var dbGlobals = new Object(); dbGlobals.db = null; dbGlobals.description = "This database is us ...
- String、StringBuffer和StringBuilder的区别
1 String String:字符串常量,字符串长度不可变.Java中String是immutable(不可变)的. String类的包含如下定义: /** The value is used fo ...
- I2C总线之(三)---以C语言理解IIC
为了加深对I2C总线的理解,用C语言模拟IIC总线,边看源代码边读波形: 如下图所示的写操作的时序图: 读时序的理解同理.对于时序不理解的朋友请参考“I2C总线之(二)---时序” 完整的程序如下: ...
- ubuntu下virtualbox使用u盘
1.virtualbox中使用u盘流程 以下是使用U盘的整个流程(参考了网络上其他人的教程,亲测可用): 添加当前用户为vboxusers一员 终端输入:cat /etc/group |grep vb ...
- vs查看虚函数表和类内存布局
虚继承和虚基类 虚继承:在继承定义中包含了virtual关键字的继承关系: 虚基类:在虚继承体系中的通过virtual继承而来的基类,需要注意的是:class CSubClass : publ ...
- python手记(32)
#!/usr/bin/env python #-*- coding: utf-8 -*- import cv2 import numpy as np fn="test2.jpg" ...
- 14.6.7 Configuring the Number of Background InnoDB IO Threads 配置InnoDB IO Threads的数量
14.6.7 Configuring the Number of Background InnoDB IO Threads 配置InnoDB IO Threads的数量 InnoDB 使用后台线程来服 ...
- 14.5.5 Deadlocks in InnoDB
14.5.5 Deadlocks in InnoDB 14.5.5.1 An InnoDB Deadlock Example 14.5.5.2 Deadlock Detection and Rollb ...
- ExecuteScalar的学习日志
一:今天写关于调用sqlhelper类的时候出现了一个异常,我仔细观察没有错误啊,怎么回事:看图 二:出现错误时id的结果是0,也就是说ExcuteScalar的结果是null,明明数据库里有多行数据 ...
- Linux的IP设置参考
位置:etc/network/interfaces 内容: 第一段是网口1自动从DHCP处获得IP 第二段是网口2静态分配IP 如果是IPv6,请把 iface eth0 inet dhcp(stat ...