作为一名刚毕业大学生,ASP.NET实战这一块还是经验欠缺,知识明显不足。之前做的更新图片,自己是用ASP.NET的控件,利用Button的onclick事件,通过刷新页面的方式来更新html img ,这种方式带来的用户体验较差,当时不会ajax,我想到了用线程的方式实时检测fileupload,却找不到监听哪个事件,用线程实时检测的结果仍为空,就不了了之了,然后看项目就去学习了点ajax(异步的javascript+xml)。但发现调用网上的一些方案,都会出一些奇怪的问题。最后终于一步一步摸索出来了,现给出自己的解决方案。
以下先贴出javascript中的代码。
$('#NewsImg').change(function () {
alert("1");
var fileObj = document.getElementById("NewsImg").files[0]; // js 获取文件对象
if (typeof (fileObj) == "undefined" || fileObj.size <= 0) {
alert("请选择图片");
return;
}
var formFile = new FormData();
formFile.append("file", fileObj); //加入文件对象
var data = formFile;
$.ajax({
url: "UpImg.ashx",
data: data,
type: "Post",
dataType: "text", //返回的数据类型
cache: false,//上传文件无需缓存
processData: false,//用于对data参数进行序列化处理 这里必须false
contentType: false, //必须
success: function (result) {
if (result != "文件上传失败") {
$("#previewImage").attr("src", "image/" + result);
}
else {
alert(result);
}
}
});
});
1,
var fileObj = document.getElementById("NewsImg").files[0]; // js 获取文件对象
如果不把图片文件获取到后放进data 里面,在ashx文件中直接用HttpFileCollection files = context.Request.Files;获得的files为NULL,所以需要用到
var fileObj = document.getElementById("NewsImg").files[0]; // js 获取文件对象
2,
processData: false,//必须
不希望转换的信息,请设置为 false。
3,
contentType: false, //必须
因为 table标签中设置了enctype = “multipart/form-data”
,这样请求中的 contentType 就会默认为 multipart/form-data 。而我们在 ajax 中 contentType 设置为 false 是为了避免 JQuery 对其操作,从而失去分界符,而使服务器不能正常解析文件。
4,
success: function (result) {
if (result != "文件上传失败") {
$("#previewImage").attr("src", "image/" + result);
}
else {
alert(result);
}
}
是请求成功接收ashx文件返回的内容。
dataType: "text", //返回的数据类型
这是声明ashx返回的内容为text也就是string类型。
以下贴出ashx文件中的代码
context.Response.ContentType = "text/plain";
string result = string.Empty;
string filePath = string.Empty;
string fileNewName = string.Empty;
HttpFileCollection files = context.Request.Files;
// HttpPostedFile file = context.Request.Files["file"]; 这种方式也可以取到值
if (files.Count > 0)
{
//设置文件名
fileNewName = DateTime.Now.ToString("yyyyMMddHHmmssff") + "_" + System.IO.Path.GetFileName(files[0].FileName);
//保存文件
files[0].SaveAs(context.Server.MapPath("~/image/" + fileNewName));
result = fileNewName;
}
else
{
result = "文件上传失败";
}
context.Response.Write(result);
context.Response.End();
5,可以打断点进入ashx中调试看拿到的值。看哪一步出错了,在前端中可以用alert();提示出自己哪一步没有执行下去,检查出自己的错误在哪。
6,最后成功解决了这个问题。