當前位置:首頁 » 文件管理 » ajax上傳

ajax上傳

發布時間: 2022-01-08 17:58:48

⑴ JS怎樣用AJAX上傳文件

可以使用jquery的uploadfild插件,或者jquery upload插件進行附件上傳,兩種插件的實現原理差不多,可以進行參考。

⑵ ajax可以實現圖片上傳嗎

可以實現。

1:先說我們平時接觸到的介面都是後台需要你給他傳遞幾個參數,你就把參數對應的值 給他們就行了

eg:


⑶ ajax+html實現文件上傳有哪幾種方法

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>大文件切割上傳</title>
<link rel="stylesheet" href="">
<script>
function selfile(){
const LENGTH = 1024 * 1024 * 10;//每次上傳的大小
var file = document.getElementsByName('video')[0].files[0];//文件對象
var filename=document.getElementsByName('video')[0].files[0].name;
var totalSize = file.size;//文件總大小
var start = 0;//每次上傳的開始位元組
var end = start + LENGTH;//每次上傳的結尾位元組
var fd = null//創建表單數據對象
var blob = null;//二進制對象
var xhr = null;//xhr對象
while(start < totalSize){
fd = new FormData();//每一次需要重新創建
xhr = new XMLHttpRequest();//需要每次創建並設置參數
xhr.open('POST','upload.php',false);
blob = file.slice(start,end);//根據長度截取每次需要上傳的數據
fd.append('video',blob);//添加數據到fd對象中
fd.append('filename',filename); //獲取文件的名稱
xhr.send(fd);//將fd數據上傳

//重新設置開始和結尾
start = end;
end = start + LENGTH;

}

}
</script>
</head>
<body>
<h1>大文件切割上傳</h1>
<input type="file" name="video" onchange="selfile();" />
</body>
</html>

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

⑸ 怎麼用ajax上傳文件

表單提交啊<input type="file" />

⑹ 如何用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.獲取之後怎麼處理自己看著辦咯,我只能幫到這里了

⑺ js、ajax怎樣上傳

ajaxfileupload.js插件的使用很簡單。
前台HTML代碼類似:
<script type="text/javascript">$(#buttonUplod).click(function () { $.ajaxFileUpload ({ url:'doajaxfileupload.php', //你處理上傳文件的服務端 secureuri:false, //與頁面處理代碼中file相對應的ID值 fileElementId:'img', dataType: 'json', //返回數據類型:text,xml,json,html,scritp,jsonp五種 success: function (data) { alert(data.file_infor); } })});</script><input id="img" type="file" size="45" name="img" ><button id="buttonUpload" onclick="return ajaxFileUpload();">Upload</button>

後台doajaxfileupload.php腳本
<?php $upFilePath = "../attachment/";$ok=@move_uploaded_file($_FILES['img']['tmp_name'],$upFilePath); if($ok === FALSE){ echo json_encode('file_infor'=>'上傳失敗'); }else{ echo json_encode('file_infor'=>'上傳成功'); }?>

為了測試,可以使用類似下面的方式保存傳遞過來的變數值:
$file_info = var_export($_FILES,true);
$ok = file_put_contents("../attachment/file_info.txt",$file_info);
if ($ok) exit(json_encode('file_infor'=>'上傳成功'));
exit (json_encode('file_infor'=>'上傳失敗'));

※ 注意
請留意HTML代碼文件框中的標記:
1. id='img'是用於給ajaxfileupload.js插件的fileElementId:'img'識別的,jQuery選擇器會利用該字元串獲得文本框的值;
2. name='img'是用於通過post方式提交到後台腳本時,PHP通過$_FILES['img']讀取上傳文件的數據,若沒有該值,$_FILES變數為空;

⑻ 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實現上傳文件的功能

HTTP File Server

http-file-server是用 python 實現的 HTTP 文件伺服器,支持上傳和下載文件。

運行

$ python file-server.py files 8001

其中第一個參數files是存放文件的路徑,第二個參數8001是 HTTP 伺服器埠。

介面

1. 讀取文件

GET /pathtofile/filename

2. 讀取文件夾下所有文件(已經忽略隱藏文件)

GET /path

返迴文件列表為JSON數組,文件名末尾帶有/的表示是文件夾。filename為文件名,mtime為修改時間。

[{"filename":"f1.txt","mtime":1001},{"filename":"p3/","mtime":1002}]

3. 上傳文件

採用POST方式上傳文件,URL參數中傳參數name表示上傳的文件名,POST內容為文件內容。

POST /upload?name=filename

ajax示例:

// file is a FileReader object
var data = file.readAsArrayBuffer();
var xhr = new XMLHttpRequest();
var url = "http://localhost:8001/upload?name=xxx.md";
xhr.open("post", url, true);
xhr.setRequestHeader("Accept", "application/json, text/javascript, */*; q=0.01");
xhr.onreadystatechange = function() {
if (xhr.readyState==4 && xhr.status==200)
{
console.log(xhr.responseText);
}
}
xhr.send(data);

文件名 filename 可以包含相對路徑。比如:upload?name=md/xxx.md。則上傳至md目錄下。

熱點內容
日誌伺服器如何分ip地址保存 發布:2024-05-20 14:46:50 瀏覽:262
如何阻止安卓自啟動 發布:2024-05-20 14:30:16 瀏覽:350
天翼雲伺服器監控 發布:2024-05-20 14:30:14 瀏覽:563
什麼游戲開伺服器便宜 發布:2024-05-20 14:21:48 瀏覽:656
萬網資料庫清空 發布:2024-05-20 14:20:46 瀏覽:557
編譯原理什麼是規范句型 發布:2024-05-20 14:08:59 瀏覽:562
jenkins自動化測試腳本 發布:2024-05-20 13:28:03 瀏覽:918
網游機戰腳本 發布:2024-05-20 13:26:56 瀏覽:482
天天愛消除卡心腳本 發布:2024-05-20 13:01:00 瀏覽:124
python中str的意思 發布:2024-05-20 13:00:52 瀏覽:235