当前位置:首页 » 文件管理 » 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目录下。

热点内容
单片机android 发布:2024-09-20 09:07:24 浏览:762
如何提高三星a7安卓版本 发布:2024-09-20 08:42:35 浏览:661
如何更换服务器网站 发布:2024-09-20 08:42:34 浏览:309
子弹算法 发布:2024-09-20 08:41:55 浏览:286
手机版网易我的世界服务器推荐 发布:2024-09-20 08:41:52 浏览:815
安卓x7怎么边打游戏边看视频 发布:2024-09-20 08:41:52 浏览:160
sql数据库安全 发布:2024-09-20 08:31:32 浏览:91
苹果连接id服务器出错是怎么回事 发布:2024-09-20 08:01:07 浏览:505
编程键是什么 发布:2024-09-20 07:52:47 浏览:655
学考密码重置要求的证件是什么 发布:2024-09-20 07:19:46 浏览:479