jsajax圖片上傳
Ⅰ 用js、jquery如何實現上傳圖片的預覽
$("#btnLoadPhoto").upload({ url: "../UploadForms/RequestUpload.aspx?action=photo", type: "json", callback: calla });
//獲得表單元素
HttpPostedFile oFile = context.Request.Files[0];
//設置上傳路徑
string strUploadPath = "temp/";
//獲取文件名稱
string fileName = context.Request.Files[0].FileName;
補充:JQuery是繼prototype之後又一個優秀的javascript庫。它是輕量級的js庫 ,它兼容CSS3,還兼容各種瀏覽器(IE 6.0+, FF 1.5+, Safari 2.0+, Opera 9.0+),jQuery2.0及後續版本將不再支持IE6/7/8瀏覽器。jQuery使用戶能更方便地處理HTML(標准通用標記語言下的一個應用)、events、實現動畫效果,並且方便地為網站提供AJAX交互。jQuery還有一個比較大的優勢是,它的文檔說明很全,而且各種應用也說得很詳細,同時還有許多成熟的插件可供選擇。jQuery能夠使用戶的html頁面保持代碼和html內容分離,也就是說,不用再在html裡面插入一堆js來調用命令了,只需要定義id即可。
Ⅱ js中動態添加的Input file 控制項,我怎麼獲取到它上傳的圖片呢請教各位大神!
方法一:你可以把你上傳的圖片,放到資料庫中的某個表中,然後,你查詢表獲得;
方法二:你上傳圖片成功以後,返回jsp 一個上傳圖片放置的路徑,你把這個路徑setValue到
<input id="tee" type="hidden"/>
通過$("#tee").val()獲得路徑,通過ajax,在後台通過url獲得圖片;
Ⅲ ajax上傳圖片,C#編寫的webserbice接收,無法上傳
不是這樣上傳的,你就傳個圖片路徑伺服器怎麼能獲取到客戶端的文件?
如果需要ajax非同步上傳圖片,有兩種解決方案,
一、採用HTML5的FileReader的readAsDataURL獲取圖片的base64編碼,獲取出來是一個字元串,把這個字元串上傳到伺服器,伺服器接收到採用Convert.FromBase64String獲取圖片byte數組,再轉換成圖片格式保存。
二、使用隱藏form表單和隱藏iframe,將form的target屬性設置為iframe的name,在from表單里放一個file控制項,用它選擇圖片,然後提交form表單,後台接收到圖片保存,返回一段js代碼,類似window.parent.uploadCallback({"state":1,"url":"你保存圖片的路徑"});,然後在頁面寫一個function uploadCallback(result){//處理回調}
不知道有沒有更好的解決辦法,我用過的就這兩種,感覺都挺好用。
Ⅳ 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上傳。
這篇文章到這里也就結束了,這篇文章包含了一些瀏覽器中提供的對象,可以看到都是很簡單的內容。
Ⅳ 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" />');
Ⅵ jquery如何將頁面生成的圖片上傳到伺服器
File Upload組件啊,是同步還是非同步呢
html部分:
<input type="file" name="file" class="webuploader-element-invisible" multiple="multiple" accept="image/*">
文件引入:
<link rel="stylesheet" type="text/css" href="diyUpload/css/diyUpload.css"><script type="text/javascript" src="diyUpload/js/diyUpload.js"></script>
HTML部分:
<div id="demo"> <div id="as" ></div></div>
JS部分:
<script type="text/javascript">
/** 伺服器地址,成功返回,失敗返回參數格式依照jquery.ajax習慣;* 其他參數同WebUploader*/
$('#as').diyUpload({
url:'server/fileupload.php',
success:function( data ) {
console.info( data ); },
error:function( err ) {
console.info( err );
},
buttonText : '選擇文件', chunked:true, // 分片大小
chunkSize:512 * 1024, //最大上傳的文件數量, 總文件大小,單個文件大小(單位位元組);
fileNumLimit:50,
fileSizeLimit:500000 * 1024,
fileSingleSizeLimit:50000 * 1024,
accept: {}});
</script>
Ⅶ ajax上傳文件提交時,enctype=multipart/form-data怎麼帶過去
form中的欄位,加上get set方法
private FormFile file;
private String filename;
private String filesize;
action 部分:
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
String dir="D:/";
UpFileForm uff=(UpFileForm)form;
FormFile file=uff.getFile();
if(file.getFileSize()==0){
return mapping.findForward("success");
}
String fname=file.getFileName();
String size=Integer.toString(file.getFileSize())+"bytes";
InputStream streamIn=file.getInputStream();
OutputStream streamOut=new FileOutputStream(dir+"/"+fname);
int bytesRead=0;
byte[] buffer=new byte[8192];
while((bytesRead=streamIn.read(buffer,0,8192))!=-1){
streamOut.write(buffer,0,bytesRead);
}
streamOut.close();
streamIn.close();
uff.setFilename(fname);
uff.setFilesize(size);
file.destroy();
return mapping.findForward("success");
}
這樣將上傳的文件存在d盤。
Ⅷ 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);}
}
}
Ⅸ 如何用ajax上傳文件
引入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.獲取之後怎麼處理自己看著辦咯,我只能幫到這里了