步骤:
1,先引用脚本,ajaxfileupload.js和配套的jquery(注意:这里如果版本不同可能会出错)
2,客户端部分代码:
<div class="jumbotron"> <h1>ASP.NET</h1> <input type="file" name="image" id="image" style="width:350px;height:25px;" /> <img src="~/Content/Image/loading.gif" style="width:100px;height:100px; display:none;" /> <br /> <input type="submit" value="提交" οnclick="javascript:uploadimage()" /> <div id="showimage" style="display:none;"> <img id="imagebox" style="width:300px;height:300px;" /> </div></div>
3,客户端的脚本部分:
function uploadimage() {
$("#loading") .ajaxStart(function () { $(this).show(); }) .ajaxComplete(function () { $(this).hide(); });$.ajaxFileUpload({
type: 'post', url: '/UpLoad/UploadImage', secureuri: false, fileElementId: 'image', dataType: 'text/html', success: function (data, textstatus) { document.getElementById("showimage").style.display = "block"; $("#imagebox").attr("src", data);},
error: function (data,status) {alert("ERROR:"+data);
} }) } 这里测试的时候将datatype设置为json格式的出错,返回的数据会自动加上<pre>标签,所以本文采用datatype:text/html数据类型。 4,处理控制器端的代码:[HttpPost] public ContentResult UploadImage(HttpPostedFileBase image) {
image = HttpContext.Request.Files["image"];
if (image != null) { string upAddress = Server.MapPath("~/Content/Image/"); int rn = new Random().Next(0, 100000); string finalUploadAddress = upAddress + rn.ToString() + System.IO.Path.GetFileName(image.FileName); image.SaveAs(finalUploadAddress); Response.ContentType = "text/html"; return Content( "/Content/Image/" + rn.ToString() + System.IO.Path.GetFileName(image.FileName),"text/html",System.Text.Encoding.UTF8 );}
else { return Content("传入了空值" ); } }