Jquery实现异步上传图片

利用jQuery的ajax函数就可以实现异步上传图片了。一开始我是想在处理程序中,直接用context.Request.Files来获取页面中的input file,但是不知道为什么一次获取不了。网上说的,Form中要设置enctype="multipart/form-data"和 method="post",input file中要加runat="server",但都加了依然获取不到。哪位大侠知道的,求指教啊。

既然后台获取不到Input file怎么办呢。其实我们上传文件,主要是获取到文件的物理地址就行了。只要有了这个文件地址就可以用bitmap获取到这个图片了。

刚开始我是想用ajax GET来传送地址,,但TMD如果文件名有中文就乱码了。好在后面改成POST后就可以成功传送了。

话不多说,上代码:

前台:

<html xmlns=""><head id="Head1" runat="server"><title></title><script src="Scripts/jquery-1.3.2-vsdoc2.js" type="text/javascript"></script><script type="text/javascript">function uploadImage() {//判断是否有选择上传文件var imgPath = $("#uploadFile").val();if (imgPath == "") {alert("请选择上传图片!");return;}//判断上传文件的后缀名var strExtension = imgPath.substr(imgPath.lastIndexOf(‘.’) + 1);if (strExtension != ‘jpg’ && strExtension != ‘gif’&& strExtension != ‘png’ && strExtension != ‘bmp’) {alert("请选择图片文件");return;}$.ajax({type: "POST",url: "handler/UploadImageHandler.ashx",data: { imgPath: $("#uploadFile").val() },cache: false,success: function(data) {alert("上传成功");$("#imgDiv").empty();$("#imgDiv").html(data);$("#imgDiv").show();},error: function(XMLHttpRequest, textStatus, errorThrown) {alert("上传失败,请检查网络后重试");}});}</script></head><body><form enctype="multipart/form-data" method="post"><input type="file" id="uploadFile" runat="server" /><input type="button" id="btnUpload" value="确定" onclick="uploadImage()" /><div id="imgDiv"></div></form></body></html>后台中的ashx:

public void ProcessRequest (HttpContext context) {//不知道为什么获取不到//HttpPostedFile file = context.Request.Files["userFile"];string filePath = context.Request["imgPath"];string path = "UploadImgs\\";Bitmap map = new Bitmap(filePath);string fileName = Path.GetFileName(filePath);string mapPath = context.Server.MapPath("~");string savePath = mapPath + "\\" + path + fileName;map.Save(savePath);//上传成功后显示IMG文件StringBuilder sb = new StringBuilder();sb.Append("<img id=\&;imgUpload\&; src=\&;"+path.Replace("\\","/")+fileName+"\&; />");context.Response.Write(sb.ToString());context.Response.End();}public bool IsReusable {get {return false;}}

人生伟业的建立,不在能知,乃在能行。

Jquery实现异步上传图片

相关文章:

你感兴趣的文章:

标签云: