2014-07-23 19:52:40|?次阅读|上传:wustguangh【已有?条评论】发表评论
使用ASP.net设计网站时,使用Ajax和JQuery结合可以使得我们上传文件的时候有更好的用户体验,为了使用JQuery实现Ajax文件上传,需要使用另一个插件ajaxFileUpload,还需要设计对应的ashx后台页面。
新建一个asp.net页面,在其中添加一个html控件
<input type="file" id="fileToUpload" name="fileToUpload" />
在对应的js脚本文件中编写javascript代码如下:
$.ajaxFileUpload({
url: 'AjaxUpload.ashx', //一个asp。net内部代码文件 看下面的介绍
secureuri: false,
fileElementId: 'fileToUpload', //此页面的html上传文件控件 fileToUpload
dataType: 'text', //文件传输类型
success: function(result) {
//alert($(result).text());
var d = $(result).text().split(","); //.ashx文件返回 的数据带有html标签,比较奇怪,故用jquery分离数据出来
if ($(":radio:checked").attr("title") == "图片") {
$ids.each(function() {
$(this).closest("tr").find("img[title=" + $(":radio:checked").val() + "]").attr("src", "../../uploadProduceFile/" + d[1]);
$(this).closest("tr").find("input[title=" + $(":radio:checked").val() + "]").val(d[0]);
});
}
if ($(":radio:checked").attr("title") == "附件") {
$ids.each(function() {
$(this).closest("tr").find("a[title=" + $(":radio:checked").val() + "]").attr("href", "../../uploadProduceFile/" + d[1]).text("打开附件");
$(this).closest("tr").find("input[title=" + $(":radio:checked").val() + "]").val(d[0]);
});
}
$("#dec").show("slow").text("成功上传所选文件");
},
error: function(result, status, e) { //上传文件异常处理
if (status == 'error') {
alert(e);
}
}
});
注意:ajaxFileUpload是一个使用了JQuery实现的第三方插件,你需要先下载该插件,为了该代码正确运行,在之前你需要引入 jquery.js 和 ajaxfileupload.js这两个js文件。