第一步:导入ajaxfileupload.js文件
第二步:新建一个aspx,在body里面创建一个文件域,一个上传按钮
<body> <input type="file" name="file" id="fileId" /> <input type="button" value="上传" id="uploadBtn" /> <br /> <img src="" id="img" /> </body>
第三步:客户端代码
<script> $(function () { $("#uploadBtn").click(function () { $.ajaxFileUpload({ url: 'FileUpload.ashx',//执行上传处理的文件地址 fileElementId: 'fileId',//file控件的id属性的值,要求这个控件要有name属性,用于在服务器端接收 success: function (data) {//成功的回调函数,内部处理会加上html标签, $("#img").attr("src", $(data).text()); } }); }); }); //$.ajaxFileUpload({ // url: 'PhotoGet.ashx',//执行上传处理的文件地址 // secureuri: false,//是否加密,一般是false,默认值为false // fileElementId: 'UploadImg',//file控件的id属性的值,要求这个控件要有name属性,用于在服务器端接收 // data: {//额外传递的数据,使用json,此时必须设置type为post // type: 1 // }, // type: 'post',//请求方式,如果传递额外数据,必须是post // success: function (data) {//成功的回调函数,内部处理会加上html标签,data是DOM对象,通过$(data)转成html标签 // $("#img1").attr("src", $(data).text()); // } //}); </script>
第四步:服务端代码
public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; int type = int.Parse(context.Request["type"]); if (type == 2) { CaptureImage(context); } else if (type == 1) { UploadImageFile(context); } } private void CaptureImage(HttpContext context) { int x1 = int.Parse(context.Request["x1"]); int y1 = int.Parse(context.Request["y1"]); int width = int.Parse(context.Request["width"]); int height = int.Parse(context.Request["height"]); Bitmap smallImg = new Bitmap(width,height); Graphics gh = Graphics.FromImage(smallImg); string bigImgPath = context.Request["img"]; Bitmap bigImg = new Bitmap(context.Request.MapPath(bigImgPath)); gh.DrawImage(bigImg, new Rectangle(0, 0, width, height), new Rectangle(x1, y1, width, height), GraphicsUnit.Pixel); string bigImgFileName = Path.GetFileName(bigImgPath); string bigImgExten = Path.GetExtension(bigImgPath); string smallPath = context.Request.MapPath(bigImgPath.Substring(0, bigImgPath.IndexOf(bigImgExten)) + "_" + "portrait" + bigImgExten); smallImg.Save(smallPath,System.Drawing.Imaging.ImageFormat.Jpeg); } private static void UploadImageFile(HttpContext context) { HttpPostedFile file = context.Request.Files["file"]; if (file != null) { string fileName = Path.GetFileName(file.FileName); string fileExten = Path.GetExtension(fileName); if (fileExten == ".jpg") { string dir = "/ImageUpload/" + DateTime.Now.Year + "/" + DateTime.Now.Month + "/" + DateTime.Now.Day + "/"; if (!Directory.Exists(context.Request.MapPath(dir))) { Directory.CreateDirectory(context.Request.MapPath(dir)); } string fullFilePath = dir + Guid.NewGuid().ToString() + "_" + fileName; file.SaveAs(context.Request.MapPath(fullFilePath)); context.Response.Write(fullFilePath); } } }