1.引用jQuery及ajaxfileupload.js
2.js
<script type="text/javascript"> $(function () { $(":button").click(function () { ajaxFileUpload(); }) }) function ajaxFileUpload() { $.ajaxFileUpload ( { url: '../ashx/upload.aspx', secureuri: false, fileElementId: 'file1', data: { "id": '123', "name": 'aaa' }, dataType: 'json', success: function (data, status) { $("#img1").attr("src", data.imgurl); if (typeof (data.error) != 'undefined') { if (data.error != '') { //alert(data.error); } else { //document.getElementById("ltlCon").innerHTML = data.imgurl; } } }, error: function (data, status, e) { //alert(e); } } ) return false; } </script>
3.html
<input type="file" id="file1" onchange="ajaxFileUpload()" name="file" class="imgup" accept="image/*"/>
4.upload.aspx
protected void Page_Load(object sender, EventArgs e) { string picName = "a"; try { picName = Request.Form["name"].ToString(); } catch (Exception) { picName = "b"; } HttpFileCollection files = Request.Files; string msg = string.Empty; string error = string.Empty; string imgurl; if (files.Count > 0) { string uploadName = System.IO.Path.GetFileName(files[0].FileName); int idx = uploadName.LastIndexOf("."); string suffix = uploadName.Substring(idx); files[0].SaveAs(Server.MapPath("/updata/yubao/") + picName + ".jpg"); msg = " 成功! 文件大小为:" + files[0].ContentLength; imgurl = "" + files[0].FileName; string res = "{ error:'" + error + "', msg:'" + picName + "',imgurl:'/updata/yubao/" + picName + ".jpg'}"; Response.Write(res); Response.End(); } }