當前位置:首頁 » 文件管理 » 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 20:20:40 瀏覽:297
python在類中定義函數調用函數 發布:2025-02-04 20:14:47 瀏覽:594
安卓手機的壁紙是哪個 發布:2025-02-04 20:14:44 瀏覽:198
java發展前景 發布:2025-02-04 20:10:19 瀏覽:76
mac登陸密碼哪裡設置 發布:2025-02-04 19:50:20 瀏覽:525
手游腳本封號 發布:2025-02-04 19:42:12 瀏覽:435
玩單機游戲要哪些配置的電腦 發布:2025-02-04 19:17:41 瀏覽:1003
c語言編程圖書 發布:2025-02-04 19:01:52 瀏覽:898
在哪裡開啟密碼顯示 發布:2025-02-04 18:38:30 瀏覽:791
怎麼查詢qq密碼 發布:2025-02-04 18:20:10 瀏覽:516