当前位置:首页 » 文件管理 » js的ajax文件上传

js的ajax文件上传

发布时间: 2023-07-08 23:35:00

A. 原生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);

        }

B. ajax如何 实现 文件上传

java">


程序说明

使用说明

实例化时,第一个必要参数是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);}
}
}

C. 如何用ajax上传文件

  1. 引入ajaxfileupload.js

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.获取之后怎么处理自己看着办咯,我只能帮到这里了

D. 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" />');

E. 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。

F. 使用jquery.form.js实现文件上传及进度条前端代码

ajax的表单提交只能提交data数据到后台,没法实现file文件的上传还有展示进度功能,这里用到form.js的插件来实现,搭配css样式简单易上手,而且高大上,推荐使用。

需要解释下我的结构, #upload-input-file 的input标签是真实的文件上传按钮,包裹form标签后可以实现上传功能, #upload-input-btn 的button标签是展示给用户的按钮,因为需要样式的美化。上传完成生成的文件名将会显示在 .upload-file-result 里面, .progress 是进度条的位置,先让他隐藏加上 hidden 的class, .progress-bar 是进度条的主体, .progress-bar-status 是进度条的文本提醒。

去掉hidden的class,看到的效果是这样的
[图片上传失败...(image-2c700a-1548557865446)]

将上传事件绑定在file的input里面,绑定方式就随意了。
var progress = $(".progress-bar"), status = $(".progress-bar-status"), percentVal = '0%'; //上传步骤 $("#myupload").ajaxSubmit({ url: uploadUrl, type: "POST", dataType: 'json', beforeSend: function () { $(".progress").removeClass("hidden"); progress.width(percentVal); status.html(percentVal); }, uploadProgress: function (event, position, total, percentComplete) { percentVal = percentComplete + '%'; progress.width(percentVal); status.html(percentVal); console.log(percentVal, position, total); }, success: function (result) { percentVal = '100%'; progress.width(percentVal); status.html(percentVal); //获取上传文件信息 uploadFileResult.push(result); // console.log(uploadFileResult); $(".upload-file-result").html(result.name); $("#upload-input-file").val(''); }, error: function (XMLHttpRequest, textStatus, errorThrown) { console.log(errorThrown); $(".upload-file-result").empty(); } });

[图片上传失败...(image-3d6ae0-1548557865446)]

[图片上传失败...(image-9f0adf-1548557865446)]

更多用法可以 参考官网

G. js文件上传中遇到的知识点

在前端开发中,我们经常遇到上传文件的需求,以前都是用到时再找资料,但总是感觉对这块不熟,最近翻资料学习了一下,记录一下。

本文中涉及的知识点有:FileList对象,Blob对象,File对象,URL对象、FormData对象等。

本文参考 网道 ,总结而来。另外,强烈推荐网道,可以去 网道的官方 看看,是阮一峰大神发起的项目,提供互联网开发文档,文档非常全面易懂。

FileList对象,是一个像数组的对象,拥有length属性和item()方法,同时,它的每一项都是File对象。

input 标签,将type设为file,之后得到的files属性就是一个FileList对象。

blob 对象表示1个二进制文件的数据内容。blob对象和arraybuffer区别是,blob对象用于操作二进制文件,arraybuffer用于操作内存。

blob 对象拥有2个属性和1个方法,分别是size(单位是字节)、type属性和slice()方法。

File 对象是一种特殊的Blob 对象。它在继承了size、type属性外,还同时有name、lastModified、lastModifiedDate等几个属性。

FileList 对象中的每一项都是File 对象。

拿到File 对象之后就要进行操作,下面是操作。

URL.createObjectURL(file) 允许为File 对象创建一个临时链接,

FileReader 对象的属性和方法比较多,属性中比较重要的是result,方法中比较重要的是

FileReader 对象的所有属性和方法可以参考 这里 ,这里就不再列出来了。

在早期的互联网时候,提交数据都是用表单。表单提交数据有些缺陷,例如无法校验表单数据,会刷新整个页面等。随着Ajax的兴起,页面表单提交数据慢慢退出历史舞台,但有时上传文件时我们偶尔会用到表单提交数据。

在调用构造函数new FormData(form)构造formdata对象时需要传入form节点,如果不传入,则默认构建空表单。如果传入,则按照key=value的时候构建表单。

可以看看效果图

FormData 对象主要的方法有:

cavas压缩图片其实很简单,无非就是几个步骤:
1、选择图片,判断图片是否大于2M(用File对象的size进行判断,size的单位是字节);
2、用FileReader对象读取文件成base64,
3、然后创建Image对象,赋值src属性,在Image对象加载完成的回调里创建cavas并绘制图片(根据图片是否大于2M动态调整画布大小);
4、将cavas转成blob,拼在formdata中用ajax上传。

这篇文章到这里也就结束了,这篇文章包含了一些浏览器中提供的对象,可以看到都是很简单的内容。

H. jQuery+ajax文件上传失败,什么原因

可能文件类型被限制,可能请求地址不匹配,可能文件大小被限制,可能服务器端错误。。
你得把报错信息发出来,不然没法分析

热点内容
在哪里开启密码显示 发布:2025-02-04 18:38:30 浏览:785
怎么查询qq密码 发布:2025-02-04 18:20:10 浏览:511
python编写接口 发布:2025-02-04 18:08:30 浏览:78
怎么给游戏设置密码 发布:2025-02-04 18:03:08 浏览:926
商品存储规划 发布:2025-02-04 17:45:24 浏览:567
ios访问共享 发布:2025-02-04 17:36:33 浏览:335
javabuild 发布:2025-02-04 17:30:19 浏览:592
gnulinux编译 发布:2025-02-04 17:30:18 浏览:132
苏州阿里云服务器专网 发布:2025-02-04 17:21:05 浏览:526
如何学习php 发布:2025-02-04 17:11:55 浏览:389