首页 > Web开发 > 详细

无刷新上传图片(asp.net mvc)

时间:2015-04-01 01:35:23      阅读:259      评论:0      收藏:0      [点我收藏+]

步骤:

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="提交" onclick="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("传入了空值" );
}


}

无刷新上传图片(asp.net mvc)

原文:http://www.cnblogs.com/lichaojacobs/p/4382508.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!