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

ajax附件上传

发布时间: 2022-09-13 20:22:52

① 怎么样通过jQuery Ajax实现上传文件

Query Ajax在web应用开发中很常用,它主要包括有ajax,get,post,load,getscript等等这几种常用无刷新操作方法,接下来通过本文给大家介绍jquery ajax 上传文件处理方式。
FormData对象
XMLHttpRequest Level 2添加了一个新的接口FormData.利用FormData对象,我们可以通过javaScript用一些键值对来模拟一系列表单控件,我们还可以使用XMLHttpRequest的send()方法来异步的提交这个”表单”.比起普通的ajax,使用FormData的最大优点就是我们可以异步上传一个二进制文件.
所有主流浏览器的较新版本都已经支持这个对象了,比如Chrome 7+、Firefox 4+、IE 10+、Opera 12+、Safari 5+。之前都是用原生js的XMLHttpRequest写的请求
XMLHttpRequest方式
xhr.open("POST", uri, true);

xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
// Handle response.
alert(xhr.responseText); // handle response.
}
};
fd.append('myFile', file);
// Initiate a multipart/form-data upload
xhr.send(fd);

其实jquery的ajax也可以支持到的,关键是设置:processData 和 contentType 。
ajax方式

var formData = new FormData();
var name = $("input").val();
formData.append("file",$("#upload")[0].files[0]);
formData.append("name",name);
$.ajax({
url : Url,
type : 'POST',
data : formData,
// 告诉jQuery不要去处理发送的数据
processData : false,
// 告诉jQuery不要去设置Content-Type请求头
contentType : false,
beforeSend:function(){
console.log("正在进行,请稍候");
},
success : function(responseStr) {
if(responseStr.status===0){
console.log("成功"+responseStr);
}else{
console.log("失败");
}
},
error : function(responseStr) {
console.log("error");
}
});

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

③ asp.net中一次性选择多个文件上传 (如:163邮箱的添加附件功能)

asp.net 有一个控件叫ajaxfileupload,这个是asp.net的ajax控件。可以满足你的要求。如果想做的更炫写,可以用JQ的插件uploadify,功能很不多。

④ ajaxfileupload+springmvc上传多文件的control怎么写

1.Spring mvc

a.xml配置:

[html] view plain print?
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver" >
<!-- set the max upload size1MB 1048576 -->
<property name="maxUploadSize">
<value>52428800</value>
</property>
<property name="maxInMemorySize">
<value>2048</value>
</property>
</bean>
b. 服务器端接收解析

[java] view plain print?
public void imgUpload(
MultipartHttpServletRequest multipartRequest,
HttpServletResponse response) throws Exception {
response.setContentType("text/html;charset=UTF-8");
Map<String, Object> result = new HashMap<String, Object>();
//获取多个file
for (Iterator it = multipartRequest.getFileNames(); it.hasNext();) {
String key = (String) it.next();
MultipartFile imgFile = multipartRequest.getFile(key);
if (imgFile.getOriginalFilename().length() > 0) {
String fileName = imgFile.getOriginalFilename();
//改成自己的对象哦!
Object obj = new Object();
//Constant.UPLOAD_GOODIMG_URL 是一个配置文件路径
try {
String uploadFileUrl = multipartRequest.getSession().getServletContext().getRealPath(Constant.UPLOAD_GOODIMG_URL);
File _apkFile = saveFileFromInputStream(imgFile.getInputStream(), uploadFileUrl, fileName);
if (_apkFile.exists()) {
FileInputStream fis = new FileInputStream(_apkFile);
} else
throw new FileNotFoundException("apk write failed:" + fileName);
List list = new ArrayList();
//将obj文件对象添加到list
list.add(obj);
result.put("success", true);
} catch (Exception e) {
result.put("success", false);
e.printStackTrace();
}
}
}
String json = new Gson().toJson(result,
new TypeToken<Map<String, Object>>() {
}.getType());
response.getWriter().print(json);
}

//保存文件
private File saveFileFromInputStream(InputStream stream, String path,
String filename) throws IOException {
File file = new File(path + "/" + filename);
FileOutputStream fs = new FileOutputStream(file);
byte[] buffer = new byte[1024 * 1024];
int bytesum = 0;
int byteread = 0;
while ((byteread = stream.read(buffer)) != -1) {
bytesum += byteread;
fs.write(buffer, 0, byteread);
fs.flush();
}
fs.close();
stream.close();
return file;
}

2.关于前端代码
a.修改ajaxfileupload.js

先到官网下载该插件.

将源文件的createUploadForm的代码替换如下:

[javascript] view plain print?
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);
}
}
for (var i = 0; i < fileElementId.length; i ++) {
var oldElement = jQuery('#' + fileElementId[i]);
var newElement = jQuery(oldElement).clone();
jQuery(oldElement).attr('id', fileElementId[i]);
jQuery(oldElement).attr('name', fileElementId[i]);
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;
}
第一步高定
b. 页面代码

html:

[html] view plain print?
<input type="button" value="添加附件" onclick="createInput('more');" />
<div id="more"></div>
js:这里可以专门写封装类,以及给file加onchange事件判断文件格式。由于时间有限,未修改
[javascript] view plain print?
var count = 1;
/**
* 生成多附件上传框
*/
function createInput(parentId){
count++;
var str = '<div name="div" ><font style="font-size:12px;">附件</font>'+
' '+ '<input type="file" contentEditable="false" id="uploads' + count + '' +
'" name="uploads'+ count +'" value="" style="width: 220px"/><input type="button" value="删除" onclick="removeInput(event)" />'+'</div>';
document.getElementById(parentId).insertAdjacentHTML("beforeEnd",str);
}
/**
* 删除多附件删除框
*/
function removeInput(evt, parentId){
var el = evt.target == null ? evt.srcElement : evt.target;
var div = el.parentNode;
var cont = document.getElementById(parentId);
if(cont.removeChild(div) == null){
return false;
}
return true;
}
下面是2个修改多file用的js,用于显示和删除,可以于上面的合并精简代码:
[javascript] view plain print?
function addOldFile(data){
var str = '<div name="div' + data.name + '" ><a href="#" style="text-decoration:none;font-size:12px;color:red;" onclick="removeOldFile(event,' + data.id + ')">删除</a>'+
' ' + data.name +
'</div>';
document.getElementById('oldImg').innerHTML += str;
}

function removeOldFile(evt, id){
//前端隐藏域,用来确定哪些file被删除,这里需要前端有个隐藏域
$("#imgIds").val($("#imgIds").val()=="" ? id :($("#imgIds").val() + "," + id));
var el = evt.target == null ? evt.srcElement : evt.target;
var div = el.parentNode;
var cont = document.getElementById('oldImg');
if(cont.removeChild(div) == null){
return false;
}
return true;
}
ajax上传文件:
[javascript] view plain print?
function ajaxFileUploadImg(id){
//获取file的全部id
var uplist = $("input[name^=uploads]");
var arrId = [];
for (var i=0; i< uplist.length; i++){
if(uplist[i].value){
arrId[i] = uplist[i].id;
}
}
$.ajaxFileUpload({
url:'xxxxx',
secureuri:false,
fileElementId: arrId, //这里不在是以前的id了,要写成数组的形式哦!
dataType: 'json',
data: {
//需要传输的数据
},
success: function (data){
},
error: function(data){
}
});
}

⑤ 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怎样用AJAX上传文件

可以使用jquery的uploadfild插件,或者jquery upload插件进行附件上传,两种插件的实现原理差不多,可以进行参考。

⑦ ajax为什么要用formdata封装在提交数据

一般文件上传是使用form表单提交,通常我们提交(使用submit button)时,会把form中的所有表格元素的name与value组成一个queryString,提交到后台。这用jQuery的方法来说,就是serialize。
通过$('#postForm').serialize()可以对form表单进行序列化,从而将form表单中的所有参数传递到服务端。

但是上述方式,只能传递一般的参数,上传文件的文件流是无法被序列化并传递的。
不过如今主流浏览器都开始支持一个叫做FormData的对象,有了这个FormData,我们就可以轻松地使用Ajax方式进行文件上传了。
但是提交以后会有刷新。而且文件本身是一个二进制流。这时可以创建一个formData。然后append该文件,然后封装成一个对象,直接进行ajax提交就可以了
具体如下:
var formdata = new FormData();
formData.append('file', $('#file')[0].files[0]);
$.ajax({
url: '/upload',
type: 'POST',
cache: false,
data: formData,
processData: false,
contentType: false
}).done(function(res) {
}).fail(function(res) {});//向后台上传附件,传四个参数 postFile(parentNodeId, nodeId){ let param=new FormData();//创建 form对象 param.append('businessNo',projectNo); param.append('packageNo', "commonProject"); param.append("parentNodeId",parentNodeId); param.append("nodeId",nodeId); var uploadObject=event.target.files; console.log(uploadObject); var i; for( i in uploadObject){ param.append("file", uploadObject[i]); } //console.log(param.get('file'));//查看file,需要使用get方法,FormData私有类对象,访问不到,可以通过get判断值是否传进去 let config={ headers:{ 'Content-Type': 'multipart/form-data' } //添加表头,因为模拟form提交时,上传文件,需要 }; //this.fileList.push(e.target.files[0]); axios.post("/auditMgr/fileUp",param,config ).then((res)=>{ console.log(res.data); this.getuploadfile(); }) },

⑧ ajaxFileUpload可以同时多个input file控件一起上传吗

function addRow() { var table = document.getElementById("mytb");//获取表格对象 if (table.rows.length > 9) { alert("不能再加了,最多上传10个附件"); }

⑨ 使用jquery.form.js 提交包含附件的表单

如果你是想 ajax提交带文件的表单,那真的没法做,
基本都是用iframe模拟 异步提交的···

jquery.form.js 提交带文件的表单,也是 用iframe模拟 异步提交的

$("#btnUpload").click(function () {
8 if ($("#flUpload").val() == "") {
9 alert("请选择一个图片文件,再点击上传。");
10 return;
11 }
12 $('#UpLoadForm').ajaxSubmit({
13 success: function (html, status) {
14 var result = html.replace("<pre>", "");
15 result = result.replace("</pre>", "");
16 $("#image").attr('src', result);
17 alert(result);
18 }
19 });
20 });

⑩ html中input上传图片什么原理啊php后台怎么处理如果用ajax的话是传些什么

用input上传图片是把图片作为文件传输的,在php后台中使用 $_FILES来接收。

注意:前端的form表单除了action ,method 属性外,还要添加一个'enctype'属性,否则文件传输不成功。

<form enctype="multipart/form-data">

<input type="file" >

</form>

$_FILES接收信息 有几个属性:

name , 上传的文件名称

size ,上传的文件大小

tmp_name ,临时路径

type ,文件类型

error错误提示

error取值说明:

( 0:没问题。1/2:大小超过限制[1->超出php.ini限制。2->超出文件域max_file限制]。3:只上传部分附件(不好测试)。4:没有上传附件)

有上传信息时:$_FILES接收到的附件信息:


保存附件:把上传的文件由临时路径保存到真实的图片存储的位置。

move_uploaded_file(临时路径名附件,真实路径名附件)

热点内容
安卓手机有什么免费音乐软件 发布:2024-10-11 02:17:07 浏览:989
阿里云服务器须知 发布:2024-10-11 02:12:55 浏览:415
androidaaptexe 发布:2024-10-11 01:49:48 浏览:347
用手机怎么连wifi密码 发布:2024-10-11 01:35:29 浏览:58
微信平台无法上传图片 发布:2024-10-11 00:55:59 浏览:139
加密锁折断 发布:2024-10-10 23:57:30 浏览:148
上传活动成果 发布:2024-10-10 23:48:27 浏览:188
2345解压慢 发布:2024-10-10 23:48:26 浏览:201
php中文空格 发布:2024-10-10 23:36:26 浏览:759
cli编译器 发布:2024-10-10 23:31:12 浏览:122