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

ajax上传控件

发布时间: 2022-09-08 05:38:14

A. 如何用Ajax实现多文件上传

jquery 实现多个上传文件教程:
首先创建解决方案,添加jquery的js和一些资源文件(如图片和进度条显示等):
1
2
3
4
5
jquery-1.3.2.min.js
jquery.uploadify.v2.1.0.js
jquery.uploadify.v2.1.0.min.js
swfobject.js
uploadify.css
1、页面的基本代码如下
这里用的是aspx页面(html也是也可的)
页面中引入的js和js函数如下:
1
2
3
4
5
6
7
<script src="js/jquery-1.3.2.min.js" type="text/javascript"></script>
<script src="js/jquery.uploadify.v2.1.0.js" type="text/javascript"></script>
<script src="js/jquery.uploadify.v2.1.0.min.js" type="text/javascript"></script>
<script src="js/swfobject.js" type="text/javascript"></script>
<link href="css/uploadify.css" rel="stylesheet" type="text/css" />

</script>
js函数:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<script type="text/javascript">
$(document).ready(function () {

$("#uploadify").uploadify({
'uploader': 'image/uploadify.swf', //uploadify.swf文件的相对路径,该swf文件是一个带有文字BROWSE的按钮,点击后淡出打开文件对话框
'script': 'Handler1.ashx',// script : 后台处理程序的相对路径
'cancelImg': 'image/cancel.png',
'buttenText': '请选择文件',//浏览按钮的文本,默认值:BROWSE。
'sizeLimit':999999999,//文件大小显示
'floder': 'Uploader',//上传文件存放的目录
'queueID': 'fileQueue',//文件队列的ID,该ID与存放文件队列的div的ID一致
'queueSizeLimit': 120,//上传文件个数限制
'progressData': 'speed',//上传速度显示
'auto': false,//是否自动上传
'multi': true,//是否多文件上传
//'onSelect': function (e, queueId, fileObj) {
// alert("唯一标识:" + queueId + "\r\n" +
// "文件名:" + fileObj.name + "\r\n" +
// "文件大小:" + fileObj.size + "\r\n" +
// "创建时间:" + fileObj.creationDate + "\r\n" +
// "最后修改时间:" + fileObj.modificationDate + "\r\n" +
// "文件类型:" + fileObj.type);

// }
'onQueueComplete': function (queueData) {
alert("文件上传成功!");
return;
}

});
});
页面中的控件代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
<body>
<form id="form1" runat="server">
<div id="fileQueue">
</div>
<div>
<p>
<input type="file" name="uploadify" id="uploadify"/>
<input id="Button1" type="button" value="上传" onclick="javascript: $('#uploadify').uploadifyUpload()" />
<input id="Button2" type="button" value="取消" onclick="javascript:$('#uploadify').uploadifyClearQueue()" />
</p>
</div>
</form>
</body>
函数主要参数:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
$(document).ready(function() {
$('#fileInput1').fileUpload({
'uploader': 'uploader.swf',//不多讲了
'script': '/AjaxByJQuery/file.do',//处理Action
'cancelImg': 'cancel.png',
'folder': '',//服务端默认保存路径
'scriptData':{'methed':'uploadFile','arg1','value1'},
//向后台传递参数,methed,arg1为参数名,uploadFile,value1为对应的参数值,服务端通过request["arg1"]
'buttonText':'UpLoadFile',//按钮显示文字,不支持中文,解决方案见下
//'buttonImg':'图片路径',//通过设置背景图片解决中文问题,就是把背景图做成按钮的样子
'multi':'true',//多文件上传开关
'fileExt':'*.xls;*.csv',//文件过滤器
'fileDesc':'.xls',//文件过滤器 详解见文档
'onComplete' : function(event,queueID,file,serverData,data){
//serverData为服务器端返回的字符串值
alert(serverData);
}
});
});
后台一般处理文件:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Net;
using System.Web;
using System.Web.Services;
namespace fupload
{
/// <summary>
/// Handler1 的摘要说明
/// </summary>
public class Handler1 : IHttpHandler
{

public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";

HttpPostedFile file = context.Request.Files["Filedata"];//对客户端文件的访问

string uploadPath = HttpContext.Current.Server.MapPath(@context.Request["folder"])+"\\";//服务器端文件保存路径

if (file != null)
{
if (!Directory.Exists(uploadPath))
{
Directory.CreateDirectory(uploadPath);//创建服务端文件夹
}

file.SaveAs(uploadPath + file.FileName);//保存文件
context.Response.Write("上传成功");
}

else
{
context.Response.Write("0");
}

}

public bool IsReusable
{
get
{
return false;
}
}
}
}
以上方式基本可以实现多文件的上传,大文件大小是在控制在10M以下/。

B. 使用Ajax调用webservices完成文件上传

上传的特殊原理决定了不能直接以ajax上传,所谓的ajax上传其实是动态生成一个iframe,里面套一个页面进行提交,提交到webservice的时候执行写文件操作就行,建议你可以使用成品的第三方控件完成,可以实现显示上传进度,如uploadify之类的。

C. php 如何用ajax做文件上传

通过传统的form表单提交的方式上传文件:
[html] view plain 在CODE上查看代码片派生到我的代码片<form id= "uploadForm" action= "http://localhost:8080/cfJAX_RS/rest/file/upload" method= "post" enctype ="multipart/form-data">
<h1 >测试通过Rest接口上传文件 </h1>
<p >指定文件名: <input type ="text" name="filename" /></p>
<p >上传文件: <input type ="file" name="file" /></p>
<p >关键字1: <input type ="text" name="keyword" /></p>
<p >关键字2: <input type ="text" name="keyword" /></p>
<p >关键字3: <input type ="text" name="keyword" /></p>
<input type ="submit" value="上传"/>
</form>
不过传统的form表单提交会导致页面刷新,但是在有些情况下,我们不希望页面被刷新,这种时候我们都是使用Ajax的方式进行请求的。
Ajax的方式进行请求:
[javascript] view plain 在CODE上查看代码片派生到我的代码片$.ajax({
url : "http://localhost:8080/STS/rest/user",type : "POST",
data : $( '#postForm').serialize(),
success : function(data) {
$( '#serverResponse').html(data);
},
error : function(data) {
$( '#serverResponse').html(data.status + " : " + data.statusText + " : " + data.responseText);}
});
通常我们提交(使用submit button)时,会把form中的所有表格元素的name与value组成一个queryString,提交到后台。这用jQuery的方法来说,就是serialize。
通过$('#postForm').serialize()可以对form表单进行序列化,从而将form表单中的所有参数传递到服务端。
但是上述方式,只能传递一般的参数,上传文件的文件流是无法被序列化并传递的。
不过如今主流浏览器都开始支持一个叫做FormData的对象,有了这个FormData,我们就可以轻松地使用Ajax方式进行文件上传了。
关于FormData及其用法
FormData是什么呢?我们来看看Mozilla上的介绍。
XMLHttpRequest Level 2添加了一个新的接口FormData.利用FormData对象,我们可以通过JavaScript用一些键值对来模拟一系列表单控件,我们还可以使用XMLHttpRequest的send()方法来异步的提交这个"表单".比起普通的ajax,使用FormData的最大优点就是我们可以异步上传一个二进制文件.
所有主流浏览器的较新版本都已经支持这个对象了,比如Chrome 7+、Firefox 4+、IE 10+、Opera 12+、Safari 5+。
参见:https://developer.mozilla.org/zh-CN/docs/Web/API/XMLHttpRequest/FormDataConstructor
FormData()
想得到一个FormData对象:
var formdata = new FormData();
W3c草案提供了三种方案来获取或修改FormData。
方案1:创建一个空的FormData对象,然后再用append方法逐个添加键值对:
var formdata = new FormData();
formdata.append("name", "呵呵");
formdata.append("url", "http://www..com/");方案2:取得form元素对象,将它作为参数传入FormData对象中!
var formobj = document.getElementById("form");var formdata = new FormData(formobj);
方案3:利用form元素对象的getFormData方法生成它!
var formobj = document.getElementById("form");var formdata = formobj.getFormData()
Method
FormData.append
本方法用于向已存在的键添加新的值,如该键不存在,新建之。
语法
formData.append(name, value);
formData.append(name, value, filename);
注: 通过 FormData.append()方法赋给字段的值若是数字会被自动转换为字符(字段的值可以是一个Blob对象,一个File对象,或者一个字符串,剩下其他类型的值都会被自动转换成字符串).
参数解释
name
键 (key), 对应表单域
value
表单域的值
filename (optional)
The filename reported to the server (a USVString), when a Blob or File is passed as the second parameter. The default filename for Blob objects is "blob".
FormData.delete
将一对键和值从 FormData 对象中删除。
formData.delete(username);
FormData.get
返回给定键的第一个值
formData.append('username', 'Justin');
formData.append('username', 'Chris');
formData.get(username); // "Justin"
FormData.getAll
返回给定键的所有值
formData.append('username', 'Justin');
formData.append('username', 'Chris');
formData.getAll(username); // ["Justin", "Chris"]
FormData.has
检查是否包含给定键,返回 true 或 false
formData.has(username);
FormData.set
设置给定键的值
formData.set(name, value);
formData.set(name, value, filename);
浏览器兼容情况
来自 MDN:
Desktop
FeatureChromeFirfox(Gecko)Intenet ExplorerOperaSafariBasic support7+4.0(2.0)10+12+5+
append with filename(Yes)22.0(22.0)???
delete, get, getAll, has, setBehind FlagNot supportedNot supported(Yes)Not supportedMobile
FeatureAndroidChrome AndroidFirfox Mobile (Gecko)Firfox OS (Gecko)IE MobileOpera MobileSafari MobileBasic support3.0?4.0(2.0)1.0.1?12+?
append with filename??22.0(22.0)1.2???
delete, get, getAll, has, set(Yes)(Yes)Not supportedNot supportedNot supported(Yes)Not supported2015年06月04日发布
Ajax通过FormData上传文件
1.使用<form>表单初始化FormData对象方式上传文件HTML代码
<form id="uploadForm" enctype="multipart/form-data">
<input id="file" type="file" name="file"/>
<button id="upload" type="button">upload</button>
</form>
javascript代码
$.ajax({
url: '/upload',
type: 'POST',
cache: false,
data: new FormData($('#uploadForm')[0]),
processData: false,
contentType: false
}).done(function(res) {
}).fail(function(res) {});
这里要注意几点:
processData设置为false。因为data值是FormData对象,不需要对数据做处理。
<form>标签添加enctype="multipart/form-data"属性。
cache设置为false,上传文件不需要缓存
contentType设置为false,不设置contentType值,因为是由<form>表单构造的FormData对象,且已经声明了属性enctype="multipart/form-data",所以这里设置为false。
上传后,服务器端代码需要使用从查询参数名为file获取文件输入流对象,因为<input>中声明的是name="file"。
如果不是用<form>表单构造FormData对象又该怎么做呢?
2.使用FormData对象添加字段方式上传文件
HTML代码
<div id="uploadForm">
<input id="file" type="file"/>
<button id="upload" type="button">upload</button>
</div>
这里没有<form>标签,也没有enctype="multipart/form-data"属性。
javascript代码
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) {});
这里有几处不一样:
append()的第二个参数应是文件对象,即$('#file')[0].files[0]。
contentType也要设置为‘false’。
从代码$('#file')[0].files[0]中可以看到一个<input type="file">标签能够上传多个文件,只需要在<input type="file">里添加multiple或multiple="multiple"属性。
3.服务器端读文件
从Servlet 3.0 开始,可以通过 request.getPart() 或 request.getPars() 两个接口获取上传的文件。

D. ajaxupload为什么文件上传的控件没有办法上传两次

因为change事件被 解除绑定了,需要你在 upload成功后重建绑定事件。并且不要用jquery写 ,用原生的js
1、创建页面并编写HTML

[html] view plain
上传文档:
<div class="uploadFile">
<span id="doc"><input type="text" disabled="disabled" /></span>
<input type="hidden" id="hidFileName" />
<input type="button" id="btnUploadFile" value="上传" />
<input type="button" id="btnDeleteFile" value="删除" />
</div>

上传图片:
<div class="uploadImg">
<img id="imgShow" src="/images/nophoto.gif" />
<input type="hidden" id="hidImgName" />
<input type="button" id="btnUploadImg" value="上传" />
<input type="button" id="btnDeleteImg" value="删除" />
</div>
2、引用AjaxUpload.js文件

[html] view plain
<script src="/js/common/AjaxUpload.js" type="text/javascript"></script>
3、编写JS脚本

[java] view plain
window.onload = function() {
init(); //初始化
}

//初始化
function init() {
//初始化文档上传
var btnFile = document.getElementById("btnUploadFile");
var doc = document.getElementById("doc");
var hidFileName = document.getElementById("hidFileName");
document.getElementById("btnDeleteFile").onclick = function() { DelFile(doc, hidFileName); };
g_AjxUploadFile(btnFile, doc, hidFileName);

//初始化图片上传
var btnImg = document.getElementById("btnUploadImg");
var img = document.getElementById("imgShow");
var hidImgName = document.getElementById("hidImgName");
document.getElementById("btnDeleteImg").onclick = function() { DelImg(img, hidImgName); };
g_AjxUploadImg(btnImg, img, hidImgName);
}

var g_AjxTempDir = "/file/temp/";
//文档上传
function g_AjxUploadFile(btn, doc, hidPut, action) {
var button = btn, interval;
new AjaxUpload(button, {
action: ((action == null || action == undefined) ? '/Common/UploadHandler.ashx?fileType=file' : action),
data: {},
name: 'myfile',
onSubmit: function(file, ext) {
if (!(ext && /^(rar|zip|pdf|pdfx|txt|csv|xls|xlsx|doc|docx|RAR|ZIP|PDF|PDFX|TXT|CSV|XLS|XLSX|DOC|DOCX)$/.test(ext))) {
alert("您上传的文档格式不对,请重新选择!");
return false;
}
},
onComplete: function(file, response) {
flagValue = response;
if (flagValue == "1") {
alert("您上传的文档格式不对,请重新选择!");
}
else if (flagValue == "2") {
alert("您上传的文档大于2M,请重新选择!");
}
else if (flagValue == "3") {
alert("文档上传失败!");
}
else {
hidPut.value = response;
doc.innerHTML="<a href='" + g_AjxTempDir + response + "' target='_blank'>" + response + "</a>";
}
}
});
}
//图片上传
function g_AjxUploadImg(btn, img, hidPut) {
var button = btn, interval;
new AjaxUpload(button, {
action: '/Common/UploadHandler.ashx?fileType=img',
data: {},
name: 'myfile',
onSubmit: function(file, ext) {
if (!(ext && /^(jpg|JPG|png|PNG|gif|GIF)$/.test(ext))) {
alert("您上传的图片格式不对,请重新选择!");
return false;
}
},
onComplete: function(file, response) {
flagValue = response;
if (flagValue == "1") {
alert("您上传的图片格式不对,请重新选择!");
}
else if (flagValue == "2") {
alert("您上传的图片大于200K,请重新选择!");
}
else if (flagValue == "3") {
alert("图片上传失败!");
}
else {
hidPut.value = response;
img.src = g_AjxTempDir + response;
}
}
});
}

//删除文档
function DelFile(doc, hidPut) {
hidPut.value = "";
doc.innerHTML = "<input type=\"text\" disabled=\"disabled\" />";
}

//删除图片
function DelImg(img, hidPut) {
hidPut.value = "";
img.src = "/images/nophoto.gif";
}

4、创建/Common/UploadHandler.ashx处理程序

[csharp] view plain
<%@ WebHandler Language="C#" Class="UploadHandler" %>

using System;
using System.Web;
using System.Text.RegularExpressions;
using System.IO;

public class UploadHandler : IHttpHandler {
private string _filedir = ""; //文件目录
/// <summary>
/// 处理上传文件(1:文件格式不正确、2:文件大小不正确、3:上传失败、文件名称:上传成功)
/// </summary>
/// <param name="context"></param>
public void ProcessRequest (HttpContext context) {
_filedir = context.Server.MapPath(@"/file/temp/");
try
{
string result = "3";
string fileType = context.Request.QueryString["fileType"]; //获取上传文件类型
if (fileType == "file")
{
result = UploadFile(context); //文档上传
}
else if (fileType == "img")
{
result = UploadImg(context); //图片上传
}
context.Response.Write(result);
}
catch
{
context.Response.Write("3");//3文件上传失败
}
}

/// <summary>
/// 文档上传
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
private string UploadFile(HttpContext context)
{
int cout = context.Request.Files.Count;
if (cout > 0)
{
HttpPostedFile hpf = context.Request.Files[0];
if (hpf != null)
{
string fileExt = Path.GetExtension(hpf.FileName).ToLower();
//只能上传文件,过滤不可上传的文件类型
string fileFilt = ".rar|.zip|.pdf|.pdfx|.txt|.csv|.xls|.xlsx|.doc|.docx......";
if (fileFilt.IndexOf(fileExt) <= -1)
{
return "1";
}

//判断文件大小
int length = hpf.ContentLength;
if (length > 2097152)
{
return "2";
}

Random rd = new Random();
DateTime nowTime = DateTime.Now;
string newFileName = nowTime.Year.ToString() + nowTime.Month.ToString() + nowTime.Day.ToString() + nowTime.Hour.ToString() + nowTime.Minute.ToString() + nowTime.Second.ToString() + rd.Next(1000, 1000000) + Path.GetExtension(hpf.FileName);
if (!Directory.Exists(_filedir))
{
Directory.CreateDirectory(_filedir);
}
string fileName = _filedir + newFileName;
hpf.SaveAs(fileName);
return newFileName;
}

}
return "3";
}

/// <summary>
/// 图片上传
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
private string UploadImg(HttpContext context)
{
int cout = context.Request.Files.Count;
if (cout > 0)
{
HttpPostedFile hpf = context.Request.Files[0];
if (hpf != null)
{
string fileExt = Path.GetExtension(hpf.FileName).ToLower();
//只能上传文件,过滤不可上传的文件类型
string fileFilt = ".gif|.jpg|.php|.jsp|.jpeg|.png|......";
if (fileFilt.IndexOf(fileExt) <= -1)
{
return "1";
}

//判断文件大小
int length = hpf.ContentLength;
if (length > 204800)
{
return "2";
}

Random rd = new Random();
DateTime nowTime = DateTime.Now;
string newFileName = nowTime.Year.ToString() + nowTime.Month.ToString() + nowTime.Day.ToString() + nowTime.Hour.ToString() + nowTime.Minute.ToString() + nowTime.Second.ToString() + rd.Next(1000, 1000000) + Path.GetExtension(hpf.FileName);
if (!Directory.Exists(_filedir))
{
Directory.CreateDirectory(_filedir);
}
string fileName = _filedir + newFileName;
hpf.SaveAs(fileName);
return newFileName;
}

}
return "3";
}

#region IHttpHandler 成员

public bool IsReusable
{
get { throw new NotImplementedException(); }
}

#endregion
}

E. 怎么样通过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");
}
});

F. 使用ajaxFileUpload这个控件上传文件,返回json数据出错

用这个东西返回的data其实与一般ajax返回的不同,因为它本身就是一个模拟ajax的操作,所以只不过是对用iframe的onload事件对返回的response进行截取......

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

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

H. asp.net ajax 中的FileUpload控件怎么用

前台代码:
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" >
<ContentTemplate>
<table>
<tr>
<td >上传图片</td>
<td>
<asp:FileUpload ID="fppicFilePath" runat="server" />
</td>
</tr>
<table>
</ContentTemplate>
</asp:UpdatePanel>
前台代码:
//获取上传图片的地址,然后按当前时间重新给图片取名字
string picFilePath = DateTime.Now.Ticks.ToString() + this.fppicFilePath.FileName;
//图片放置的路径
string path = Server.MapPath("../admin_Katstar/");
this.fppicFilePath.PostedFile.SaveAs(path + picFilePath);
//添加到数据库
jobornQQpicInfo.picFilePath = picFilePath; //对应数据库的列
int row = jobornQQpicBll.Insert(jobornQQpicInfo); //添加的方法
if (row > 0)
{
ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('添加成功')</script>");
}
else
{
ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('添加失败')</script>");
}

I. AjaxUpload 上传前确认

把自动提交改为手动提交即设置为autoSubmit: true,然后在onChange里面设置返回false即可停止上传

J. ajax如何上传文件,伪ajax

没有别的好办法了,隐藏的iframe就是想起到一个看似局部刷新的功能,这方法其实挺好用的

热点内容
照片压缩美图秀秀 发布:2024-10-11 21:23:42 浏览:415
冠状病毒加密 发布:2024-10-11 21:09:21 浏览:103
服务器与浏览器是什么 发布:2024-10-11 21:09:19 浏览:581
安卓11的彩蛋游戏怎么进去 发布:2024-10-11 21:02:01 浏览:560
android最新api 发布:2024-10-11 21:01:58 浏览:737
脚本抢消费券 发布:2024-10-11 21:01:51 浏览:540
文件夹只读加密专家 发布:2024-10-11 20:40:26 浏览:867
视频缓存太慢 发布:2024-10-11 20:34:16 浏览:116
我的世界服务器为什么不能联机 发布:2024-10-11 20:34:11 浏览:828
51asp源码 发布:2024-10-11 20:33:33 浏览:541