今天公司项目需要文件上传,网上查了些资料及报的好多问题,今天顺便把他整理一下,以便以后使用和帮助需要帮助的人


HTML代码


引入js文件

jquery.min.js

ajaxfileupload.js


<table>

<tr>
<td align="center">效果图</td>
<td colspan="3">

<!--name属性必须加,我调试了半天没加name属性上传会出问题,没有拿到上传文件-->
<input type="file" id="effectimage" name="effectimage"/>
<input type="button" value="上传" onclick="uploadImageFile('effectimage','effectimageShow','/action');"/>
<div id="effectimageShow" style="width:100%;"></div>
</td>
</tr>
<tr>
<td align="center">交通图</td>
<td colspan="3">
<input type="file" id="trafficImage" name="trafficImage"/>
<input type="button" value="上传" onclick="uploadImageFile('trafficImage','trafficImageShow','/action');"/>
<div id="trafficImageShow" style="width:100%;"></div>
</td>
</tr>
<tr>
<td align="center">户型图</td>
<td colspan="3">
<input type="file" id="houseImage" name="houseImage"/>
<input type="button" value="上传" onclick="uploadImageFile('houseImage','houseImageShow','/action');"/>
<div id="houseImageShow" style="width:100%;"></div>
</td>
</tr>
<tr>
<td align="center">实景图</td>
<td colspan="3">
<input type="file" id="realImage" name="realImage"/>
<input type="button" value="上传" onclick="uploadImageFile('realImage','realImageShow','/action');"/>
<div id="realImageShow" style="width:100%;"></div>
</td>
</tr>
<tr>
<td align="center">样板房</td>
<td colspan="3">
<input type="file" id="modelImage" name="modelImage"/>
<input type="button" value="上传" onclick="uploadImageFile('modelImage','modelImageShow','/action');"/>
<div id="modelImageShow" style="width:100%;"></div>
</td>
</tr>

</table>


js文件代码


/**
* 上传图片
* @param id 上传控件id 如:<input type="file" id="trafficImage"/> id=trafficImage
* @param showId 图片上传成功后显示id
*/
function uploadImageFile(id,showId,url) {

if(!$("#"+id).val()){
alert( "请选择所要上传的文件!");
return false;
}

$.ajaxFileUpload({
url : url,
secureuri : false,
fileElementId : id,
dataType : "json",
success : function(data,status) {
alert("上传成功!");
$("#" + showId).append('<span id="'+data.id+'"><a href="' +data.href+ '">'
+ data.name + '</a>&nbsp;&nbsp;<a href="javascript:void(0);" onclick="deleteUploadImageTag(\''
+ showId +'\',\'' + data.id + '\');">删除</a>&nbsp;&nbsp;</span>');
},
error : function(data,status,e) {
alert( "上传失败:" + data.msg);
}
});

}

/**
* 删除
* @param showId
* @param spanId
*/
function deleteUploadImageTag(showId,spanId){
$('#'+ showId + ' span[id='+ spanId +']').remove();
}


ajaxfileupload.js


jQuery.extend({


createUploadIframe: function(id,uri)
{
//create frame
var frameId = 'jUploadFrame' + id;
var iframeHtml = '<iframe id="' + frameId + '" name="' + frameId + '" style="position:absolute; top:-9999px; left:-9999px"';
if(window.ActiveXObject)
{
if(typeof uri== 'boolean'){
iframeHtml += ' src="' + 'javascript:false' + '"';

}
else if(typeof uri== 'string'){
iframeHtml += ' src="' + uri + '"';

}
}
iframeHtml += ' />';
jQuery(iframeHtml).appendTo(document.body);

return jQuery('#' + frameId).get(0);
},
createUploadForm: function(id,fileElementId,data)
{
//create form
var formId = 'jUploadForm' + id;
var fileId = 'jUploadFile' + id;
var form = jQuery('<form action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>');
if(data)
{
for(var i in data)
{
jQuery('<input type="hidden" name="' + i + '" value="' + data[i] + '" />').appendTo(form);
}
}
var oldElement = jQuery('#' + fileElementId);
var newElement = jQuery(oldElement).clone();
jQuery(oldElement).attr('id',fileId);
jQuery(oldElement).before(newElement);
jQuery(oldElement).appendTo(form);



//set attributes
jQuery(form).css('position','absolute');
jQuery(form).css('top','-1200px');
jQuery(form).css('left','-1200px');
jQuery(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 = new Date().getTime()
var form = jQuery.createUploadForm(id,s.fileElementId,(typeof(s.data)=='undefined'?false:s.data));
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",s] );
} else
jQuery.handleError(s,status);
} catch(e)
{
status = "error";
jQuery.handleError(s,e);
}

// The request was completed
if( s.global )
jQuery.event.trigger( "ajaxComplete",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
{
jQuery(io).remove();
jQuery(form).remove();

} catch(e)
{
jQuery.handleError(s,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);
jQuery(form).attr('method','POST');
jQuery(form).attr('target',frameId);
if(form.encoding)
{
jQuery(form).attr('encoding','multipart/form-data');
}
else
{
jQuery(form).attr('enctype','multipart/form-data');
}
jQuery(form).submit();

} catch(e)
{
jQuery.handleError(s,e);
}

jQuery('#' + frameId).load(uploadCallback );
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" )

//返回的json串前加了这句代码<pre style="word-wrap: break-word; white-space: pre-wrap;">返回的Json<pre>
/**-----处理上传返回的json格式 start----**/
if(data.indexOf('{') != -1){
data = data.substring(data.indexOf('{'),data.lastIndexOf('}')+1);
}
/**-----处理上传返回的json格式 end----**/

eval( "data = " + data );
// evaluate scripts within html
if ( type == "html" )
jQuery("<div>").html(data).evalScripts();

return data;
},

// jquery高版本没有此函数,将低版本的此函数复制过来解决handleError错误

handleError: function( s,xhr,e ) { // If a local callback was specified,fire it if ( s.error ) { s.error.call( s.context || s,e ); } // Fire the global callback if ( s.global ) { (s.context ? jQuery(s.context) : jQuery.event).trigger( "ajaxError",[xhr,s,e] ); } } })

ajaxfileupload 文件上传的更多相关文章

  1. HTML5新增form控件和表单属性实例代码详解

    这篇文章主要介绍了HTML5新增form控件和表单属性实例代码详解,需要的朋友可以参考下

  2. jquery点赞功能实现代码 点个赞吧!

    点赞功能很多地方都会出现,如何实现爱心点赞功能,这篇文章主要为大家详细介绍了jquery点赞功能实现代码,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

  3. HTML5表单验证特性(知识点小结)

    这篇文章主要介绍了HTML5表单验证特性的一些知识点,本文通过实例代码截图的形式给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

  4. amazeui页面分析之登录页面的示例代码

    这篇文章主要介绍了amazeui页面分析之登录页面的示例代码,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

  5. 在IOS9中的Cordova应用程序使用JQuery / Javascript的window.history问题

    在两个测试用例中唯一改变的是Cordova.js.解决方法我看到这是几个星期前,但我会发布这个,以防其他人遇到它.听起来它可能与iOS9中的哈希更改生成的导航事件有关.如果是这样,可以将其添加到index.html以禁用哈希侦听:

  6. iOS 5上的jQuery事件

    解决方法在Apple开发论坛上由一个人回答:我需要在将元素添加到DOM之后才绑定(),如下所示:

  7. ios – Swift Eureka Form中的循环

    我正在构建一个Eureka表单,并希望在表单中放置一个循环来构建基于数组的步进器列表.我试图使用的代码是:但是,当我这样做时,我在StepperRow行上出现了一个错误:所以看起来Swift不再认为它在形式之内并且正在关注

  8. swift 上传图片和参数 upload image with params

    Alamofire.upload(urlRequest.0,urlRequest.1).progress{(bytesWritten,totalBytesWritten,totalBytesExpectedToWrite)inprintln("\(totalBytesWritten)/\(totalBytesExpectedToWrite)")}}

  9. swift – 使用PostgreSQL在Vapor 3中上传图片

    我正在关注这些家伙MartinLasek教程,现在我正在“图片上传”.似乎没有人能回答“如何上传iVapor3图像”的问题Db连接正常,所有其他值都保存.这是我的创建方法:和型号:}和叶子模板:我知道需要一种管理文件的方法和原始图像字节,但我怎么去那里?这使用多部分表单的自动解码:upload.leaf文件是:使用File类型可以访问上载文件的本地文件名以及文件数据.如果将其余的Question字段添加到ExampleUpload结构中,则可以使用该路径捕获整个表单的字段.

  10. android – Phonegap本地构建 – jquery ajax错误:readystate 0 responsetext status 0 statustext error

    解决方法您是否在索引文件中包含了内容安全元标记?

随机推荐

  1. xe-ajax-mock 前端虚拟服务

    最新版本见Github,点击查看历史版本基于XEAjax扩展的Mock虚拟服务插件;对于前后端分离的开发模式,ajax+mock使前端不再依赖后端接口开发效率更高。CDN使用script方式安装,XEAjaxMock会定义为全局变量生产环境请使用xe-ajax-mock.min.js,更小的压缩版本,可以带来更快的速度体验。

  2. vue 使用 xe-ajax

    安装完成后自动挂载在vue实例this.$ajaxCDN安装使用script方式安装,VXEAjax会定义为全局变量生产环境请使用vxe-ajax.min.js,更小的压缩版本,可以带来更快的速度体验。cdnjs获取最新版本点击浏览已发布的所有npm包源码unpkg获取最新版本点击浏览已发布的所有npm包源码AMD安装require.js安装示例ES6Module安装通过Vue.use()来全局安装示例./Home.vue

  3. AJAX POST数据中文乱码解决

    前端使用encodeURI进行编码后台java.net.URLDecoder进行解码编解码工具

  4. Koa2框架利用CORS完成跨域ajax请求

    实现跨域ajax请求的方式有很多,其中一个是利用CORS,而这个方法关键是在服务器端进行配置。本文仅对能够完成正常跨域ajax响应的,最基本的配置进行说明。这样OPTIONS请求就能够通过了。至此为止,相当于仅仅完成了预检,还没发送真正的请求呢。

  5. form提交时,ajax上传文件并更新到&lt;input&gt;中的value字段

  6. ajax的cache作用

    filePath="+escape;},error:{alert;}});解决方案:1.加cache:false2.url加随机数正常代码:网上高人解读:cache的作用就是第一次请求完毕之后,如果再次去请求,可以直接从缓存里面读取而不是再到服务器端读取。

  7. 浅谈ajax上传文件属性contentType = false

    默认值为contentType="application/x-www-form-urlencoded".在默认情况下,内容编码类型满足大多数情况。在这里,我们主要谈谈contentType=false.在使用ajax上传文件时:在其中先封装了一个formData对象,然后使用post方法将文件传给服务器。说到这,我们发现在JQueryajax()方法中我们使contentType=false,这不是冲突了吗?这就是因为当我们在form标签中设置了enctype=“multipart/form-data”,

  8. 909422229_ajaxFileUpload上传文件

    ajaxFileUpload.js很多同名的,因为做出来一个很容易。我上github搜AjaxFileUpload出来很多类似js。ajaxFileUpload是一个异步上传文件的jQuery插件传一个不知道什么版本的上来,以后不用到处找了。语法:$.ajaxFileUploadoptions参数说明:1、url上传处理程序地址。2,fileElementId需要上传的文件域的ID,即的ID。3,secureuri是否启用安全提交,默认为false。4,dataType服务器返回的数据类型。6,error

  9. AJAX-Cache:一款好用的Ajax缓存插件

    原文链接AJAX-Cache是什么Ajax是前端开发必不可少的数据获取手段,在频繁的异步请求业务中,我们往往需要利用“缓存”提升界面响应速度,减少网络资源占用。AJAX-Cache是一款jQuery缓存插件,可以为$.ajax()方法扩展缓存功能。

  10. jsf – Ajax update/render在已渲染属性的组件上不起作用

    我试图ajax更新一个有条件渲染的组件。我可以确保#{user}实际上是可用的。这是怎么引起的,我该如何解决呢?必须始终在ajax可以重新呈现之前呈现组件。Ajax正在使用JavaScriptdocument.getElementById()来查找需要更新的组件。但是如果JSF没有将组件放在第一位,那么JavaScript找不到要更新的内容。解决方案是简单地引用总是渲染的父组件。

返回
顶部