当前位置:首页 » 文件管理 » jsajax上传文件

jsajax上传文件

发布时间: 2023-06-02 22:51:17

① ajax能上传图片吗

有一个ajaxfileupload的组件 ajaxfileupload.js,可以异步上传文件。

② 如何用ajax上传文件

  1. 引入ajaxfileupload.js

java">jQuery.extend({


createUploadIframe:function(id,uri)
{
//createframe
varframeId='jUploadFrame'+id;

if(window.ActiveXObject){
vario=document.createElement('<iframeid="'+frameId+'"name="'+frameId+'"/>');
if(typeofuri=='boolean'){
io.src='javascript:false';
}
elseif(typeofuri=='string'){
io.src=uri;
}
}
else{
vario=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);

returnio
},
createUploadForm:function(id,fileElementId)
{
//createform
varformId='jUploadForm'+id;
varfileId='jUploadFile'+id;
varform=$('<formaction=""method="POST"name="'+formId+'"id="'+formId+'"enctype="multipart/form-data"></form>');
varoldElement=$('#'+fileElementId);
varnewElement=$(oldElement).clone();
$(oldElement).attr('id',fileId);
$(oldElement).before(newElement);
$(oldElement).appendTo(form);
//setattributes
$(form).css('position','absolute');
$(form).css('top','-1200px');
$(form).css('left','-1200px');
$(form).appendTo('body');
returnform;
},
addOtherRequestsToForm:function(form,data)
{
//addextraparameter
varoriginalElement=$('<inputtype="hidden"name=""value="">');
for(varkeyindata){
name=key;
value=data[key];
varcloneElement=originalElement.clone();
cloneElement.attr({'name':name,'value':value});
$(cloneElement).appendTo(form);
}
returnform;
},

ajaxFileUpload:function(s){
//TODOintroceglobalsettings,,notonlytimeout
s=jQuery.extend({},jQuery.ajaxSettings,s);
varid=newDate().getTime()
varform=jQuery.createUploadForm(id,s.fileElementId);
if(s.data)form=jQuery.addOtherRequestsToForm(form,s.data);
vario=jQuery.createUploadIframe(id,s.secureuri);
varframeId='jUploadFrame'+id;
varformId='jUploadForm'+id;
//Watchforanewsetofrequests
if(s.global&&!jQuery.active++)
{
jQuery.event.trigger("ajaxStart");
}
varrequestDone=false;
//Createtherequestobject
varxml={}
if(s.global)
jQuery.event.trigger("ajaxSend",[xml,s]);
//Waitforaresponsetocomeback
varuploadCallback=function(isTimeout)
{
vario=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;

}elseif(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;
varstatus;
try{
status=isTimeout!="timeout"?"success":"error";
//
if(status!="error")
{
//processthedata()
vardata=jQuery.uploadHttpData(xml,s.dataType);
//Ifalocalcallbackwasspecified,fireitandpassitthedata
if(s.success)
s.success(data,status);

//Firetheglobalcallback
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);
}

//Therequestwascompleted
if(s.global)
jQuery.event.trigger("ajaxComplete",[xml,s]);

//HandletheglobalAJAXcounter
if(s.global&&!--jQuery.active)
jQuery.event.trigger("ajaxStop");

//Processresult
if(s.complete)
s.complete(xml,status);

jQuery(io).unbind()

setTimeout(function()
{ try
{
$(io).remove();
$(form).remove();

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

},100)

xml=null

}
}
//Timeoutchecker
if(s.timeout>0)
{
setTimeout(function(){
//
if(!requestDone)uploadCallback("timeout");
},s.timeout);
}
try
{
//vario=$('#'+frameId);
varform=$('#'+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){
vardata=!type;
data=type=="xml"||data?r.responseXML:r.responseText;
//Ifthetypeis"script",evalitinglobalcontext
if(type=="script")
jQuery.globalEval(data);
//GettheJavaScriptobject,ifJSONisused.
if(type=="json")
{
//,
//youhavetodeletethe'<pre></pre>'tag.
//ThepretaginChromehasattribute,sohavetouseregextoremove
vardata=r.responseText;
varrx=newRegExp("<pre.*?>(.*?)</pre>","i");
varam=rx.exec(data);
//thisisthedesireddataextracted
vardata=(am)?am[1]:"";//theonlysubmatchorempty
eval("data="+data);
}
//evaluatescriptswithinhtml
if(type=="html")
jQuery("<div>").html(data).evalScripts();
//alert($('param',data).each(function(){alert($(this).attr('value'));}));
returndata;
}
})

2.引入上传文件所需的jar

7.获取之后怎么处理自己看着办咯,我只能帮到这里了

③ ajaxfileupload.js上传文件时后台用java怎么接收文件流

前台:ajax实现,点击上传,确认表单发送到后台,此时ajax做的事情,就是确认表单,这是一个伪ajax ,ajax不能实现文件上传,可以使用一个JS,叫做ajaxfileupload.js的用法。
后台无非是接收了,没什么好讲

④ ajax的res怎么传到其他文件

传其他参竖坦数
ajax文件上传怎么传带纤腊其他参数,Ajax进行文件与其他参数的上传功能

光启元
转载
关注
0点赞·945人阅读
记得前一段时间,为了研究Ajax文件上传,找了很多资料,在网上看到的大部分是form表单的方式提交文件,对于Ajax方式提交文件并且也要提交表单中其他数据,发现提及的并不是很多,后来在同事的帮助下,使用ajaxfileupload最终完成了文件上传与其他提交的操作,现在分享给大家,希望大家能有有所帮助。本文主要介绍了使用Ajax进行文件与其他参数的上传功能(java开发),非常不错,具有参考借鉴价值,需要的朋友参考下吧,希望能帮助到大家。

文件上传:

操作步骤:

1 导入jar包:

我们在使用文件上传时,需要使用到两个jar包,分别是commons-io与commons-fileupload,在这里我使用的两个版本分别是2.4与1.3.1版本的,需要使用JS文件与jar包最后会发给大家一个连接(如何失效请直接我给留言,我会及时更改,谢谢)。

2 修改配置文件:

当我们导入的jar包是不够的,我们需要使用到这些jar包,由于我当时使用的是SSM框架,所以我是在application-content.xml中配置一下CommonsMultipartResolver,具体配置方法如下:

104857600

4096

3 JSP文件:

大家对form表单提交问价的方式很熟悉,但是我们有很多情况下并不能直接使用form表单方式直接提交。这时候我们就需要使用Ajax方式提交,Ajax有很多的好处,比如当我们不需要刷新页面获希望进行局部蠢滑刷新的时候,我们就可以使用Ajax。

⑤ ajax如何 实现 文件上传



程序说明

使用说明

实例化时,第一个必要参数是file控件对象:

newQuickUpload(file);


第二个可选参数用来设置系统的默认属性,包括
属性: 默认值//说明
parameter:{},//参数对象
action:"",//设置action
timeout:0,//设置超时(秒为单位)
onReady:function(){},//上传准备时执行
onFinish:function(){},//上传完成时执行
onStop:function(){},//上传停止时执行
onTimeout:function(){}//上传超时时执行

还提供了以下方法:
upload:执行上传操作;
stop:停止上传操作;
dispose:销毁程序。

varQuickUpload=function(file,options){

this.file=$$(file);

this._sending=false;//是否正在上传
this._timer=null;//定时器
this._iframe=null;//iframe对象
this._form=null;//form对象
this._inputs={};//input对象
this._fFINISH=null;//完成执行函数

$$.extend(this,this._setOptions(options));
};
QuickUpload._counter=1;
QuickUpload.prototype={
//设置默认属性
_setOptions:function(options){
this.options={//默认值
action:"",//设置action
timeout:0,//设置超时(秒为单位)
parameter:{},//参数对象
onReady:function(){},//上传准备时执行
onFinish:function(){},//上传完成时执行
onStop:function(){},//上传停止时执行
onTimeout:function(){}//上传超时时执行
};
return$$.extend(this.options,options||{});
},
//上传文件
upload:function(){
//停止上一次上传
this.stop();
//没有文件返回
if(!this.file||!this.file.value)return;
//可能在onReady中修改相关属性所以放前面
this.onReady();
//设置iframe,form和表单控件
this._setIframe();
this._setForm();
this._setInput();
//设置超时
if(this.timeout>0){
this._timer=setTimeout($$F.bind(this._timeout,this),this.timeout*1000);
}
//开始上传
this._form.submit();
this._sending=true;
},
//设置iframe
_setIframe:function(){
if(!this._iframe){
//创建iframe
variframename="QUICKUPLOAD_"+QuickUpload._counter++,
iframe=document.createElement($$B.ie?"<iframename=""+iframename+"">":"iframe");
iframe.name=iframename;
iframe.style.display="none";
//记录完成程序方便移除
varfinish=this._fFINISH=$$F.bind(this._finish,this);
//iframe加载完后执行完成程序
if($$B.ie){
iframe.attachEvent("onload",finish);
}else{
iframe.onload=$$B.opera?function(){this.onload=finish;}:finish;
}
//插入body
varbody=document.body;body.insertBefore(iframe,body.childNodes[0]);

this._iframe=iframe;
}
},
//设置form
_setForm:function(){
if(!this._form){
varform=document.createElement('form'),file=this.file;
//设置属性
$$.extend(form,{
target:this._iframe.name,method:"post",encoding:"multipart/form-data"
});
//设置样式
$$D.setStyle(form,{
padding:0,margin:0,border:0,
backgroundColor:"transparent",display:"inline"
});
//提交前去掉form
file.form&&$$E.addEvent(file.form,"submit",$$F.bind(this.dispose,this));
//插入form
file.parentNode.insertBefore(form,file).appendChild(file);

this._form=form;
}
//action可能会修改
this._form.action=this.action;
},
//设置input
_setInput:function(){
varform=this._form,oldInputs=this._inputs,newInputs={},name;
//设置input
for(nameinthis.parameter){
varinput=form[name];
if(!input){
//如果没有对应input新建一个
input=document.createElement("input");
input.name=name;input.type="hidden";
form.appendChild(input);
}
input.value=this.parameter[name];
//记录当前input
newInputs[name]=input;
//删除已有记录
deleteoldInputs[name];
}
//移除无用input
for(nameinoldInputs){form.removeChild(oldInputs[name]);}
//保存当前input
this._inputs=newInputs;
},
//停止上传
stop:function(){
if(this._sending){
this._sending=false;
clearTimeout(this._timer);
//重置iframe
if($$B.opera){//opera通过设置src会有问题
this._removeIframe();
}else{
this._iframe.src="";
}
this.onStop();
}
},
//销毁程序
dispose:function(){
this._sending=false;
clearTimeout(this._timer);
//清除iframe
if($$B.firefox){
setTimeout($$F.bind(this._removeIframe,this),0);
}else{
this._removeIframe();
}
//清除form
this._removeForm();
//清除dom关联
this._inputs=this._fFINISH=this.file=null;
},
//清除iframe
_removeIframe:function(){
if(this._iframe){
variframe=this._iframe;
$$B.ie?iframe.detachEvent("onload",this._fFINISH):(iframe.onload=null);
document.body.removeChild(iframe);this._iframe=null;
}
},
//清除form
_removeForm:function(){
if(this._form){
varform=this._form,parent=form.parentNode;
if(parent){
parent.insertBefore(this.file,form);parent.removeChild(form);
}
this._form=this._inputs=null;
}
},
//超时函数
_timeout:function(){
if(this._sending){this._sending=false;this.stop();this.onTimeout();}
},
//完成函数
_finish:function(){
if(this._sending){this._sending=false;this.onFinish(this._iframe);}
}
}

⑥ 原生js实现文件上传

function saveUser() {

            var file = document.getElementById("file").files[0];

            //原生ajax实现文件上传

            var formData = new FormData();

            if (file) {

                formData.append("file", file);

                console.log(file)

            }

            //得到xhr对象

            var xhr = null;

            if (XMLHttpRequest) {

                xhr = new XMLHttpRequest();

            } else {

                xhr = new ActiveXObject("Microsoft.XMLHTTP");

            }

            xhr.open("post", "http://www-test.mianyazhu.com/supplier/fileSupplier/file/upload/supplier", true);//设置提交方式,url,异步提交

//            xhr.setRequestHeader("Content-Type","multipart/form-data");

            xhr.onload = function () {

                var data = xhr.responseText;    //得到返回值

                console.log(data);

            }

            xhr.send(formData);

        }

⑦ java 使用 AjaxUpload.js 实现上传文档的时候需要注意哪些

ajax是无法提交文件的,所以在上传图片并预览的时候,我们经常使用Ifame的方法实现看似异步的效果。但是这样总不是很方便的,AjaxFilleUpload.js对上面的方法进行了一个包装,使得我们不用去管理Iframe的一系列操作,也不用影响我们的页面结构,实现异步的文件提交。

html:
复制代码 代码如下:
<input type="file" name="upload" hidden="hidden" id="file_upload" accept=".zip" />

js:
复制代码 代码如下:
$.ajaxFileUpload({
url:'${pageContext.request.contextPath}/Manage/BR_restorePic.action', //需要链接到服务器地址
secureuri:false,
fileElementId:'file_upload', //文件选择框的id属性
dataType: 'text', //服务器返回的格式,可以是json、xml
success: function (data, status) //相当于java中try语句块的用法
{

$('#restoreDialog').html(data);

//alert(data);
},
error: function (data, status, e){ //相当于java中catch语句块的用法

$('#restoreDialog').html("上传失败,请重试");
}
});

这个方法还会出现一个问题,就是input只能使用一次的问题,input第二次的onchange将不会被执行,这应该是与浏览器的有关,解决办法就是替换这个input

像这样:
复制代码 代码如下:
$('#file_upload').replaceWith('<input type="file" name="upload" hidden="hidden" id="file_upload" accept=".zip" />');

⑧ extjs ajax 可以上传文件吗

文件上传的Ajax,首先Ajax并不支持流的传输,只是在里面套了个iframe。

//ajax上传
Ext.get('btn').on('click',function(){
Ext.Ajax.request({
url:'Upload.php',
isUpload:true,
form:'upform',
success:function(){
Ext.Msg.alert('upfile','文件上传成功!');
}
});
});
<formid="upform">
请选择文件:<inputtype="file"name="imgFile"/>
<inputtype="button"id="btn"value="上传"/>
</form>
<?php
if(!isset($_FILES['imgFile'])){
echojson_encode(array("success"=>false,'msg'=>"NotgetImgfile"));
return;
}
$upfile=$_FILES['imgFile'];
$name=$upfile["name"];//上传文件的文件名
$type=$upfile["type"];//上传文件的类型
$size=$upfile["size"];//上传文件的大小
$tmp_name=$upfile["tmp_name"];//上传文件的临时存放路径
$error_cod=$upfile["error"];
if($error_cod>0){
echojson_encode(array("success"=>false,'msg'=>$error_cod));
}
$photo_tmp_file_name=//这里设置存放路径
move_uploaded_file($tmp_name,$photo_tmp_file_name);//存储文件
?>
热点内容
android列表显示 发布:2025-02-07 17:01:19 浏览:63
芒果tv缓存的视频在哪个文件里 发布:2025-02-07 16:45:05 浏览:814
php邮件群发 发布:2025-02-07 16:45:05 浏览:612
mysql数据库基本语句 发布:2025-02-07 16:41:48 浏览:250
医院门禁密码多少 发布:2025-02-07 16:41:43 浏览:527
服务器遭美国ip攻击签名 发布:2025-02-07 16:22:48 浏览:546
如何配置二良腌料 发布:2025-02-07 16:11:54 浏览:735
数据库课程设计学生管理系统 发布:2025-02-07 16:11:50 浏览:764
美国文化密码是什么 发布:2025-02-07 16:07:14 浏览:261
安卓手机下雪特效怎么p 发布:2025-02-07 15:49:30 浏览:319