JJY

MVC 图片上传 带进度条(转)

 

MVC 图片上传小试笔记

 form.js 这个插件已经是很有名的,结合MVC的html辅助方法异步上传就很简单了。jQuery Form Plugin :http://www.malsup.com/jquery/form/#file-upload


 1.引入js,构建form。本身的BeginForm已经能够提交,但是如果有返回值的话,页面会跳转,这样体验就很不好。网上有说把反馈结果写在ViewData中,来绕开return。其实这是浏览器的默认行为,用form.js可以阻止掉。


 



@using (Html.BeginForm("Upload", "Home", FormMethod.Post, new { enctype = "multipart/form-data", name = "Form1", id = "Form1" }))
{
if (ViewData["ck"]!=null&&ViewData["ck"].ToString() != "")
{
<span id="ss">@ViewData["ck"].ToString()</span>
}
<input type="file" name="file" required="required" />
<input type="submit" name="subt" value="Upload File"/>
}

<div class="progress">
<div class="bar"></div>
<div class="percent">0%</div>
</div>
<div id="status"></div>

2.进度条与反馈结果


   在表单插件的demo中已经有很好的例子,包括同时上传多个图片: http://www.malsup.com/jquery/form/progress.html 


   在ajaxform中完全可以控制整个上传到的节奏。



<script>(function () {
var bar = $(''.bar'');
var percent = $(''.percent'');
var status = $(''#status'');
$(''#Form1'').ajaxForm({
beforeSend: function () {//上传之前设置,在这里可以写验证
status.empty();
var percentVal = ''0%'';
bar.width(percentVal);
percent.html(percentVal);
},
uploadProgress: function (event, position, total, percentComplete) {//进度条
var percentVal = percentComplete + ''%'';
bar.width(percentVal);
percent.html(percentVal);
},
success: function () {//成功之后执行
var percentVal = ''100%'';
bar.width(percentVal);
percent.html(percentVal);
}, complete: function (xhr) { status.html(xhr.responseText); }
});
})();</script>

  3.转移图片。


   文件保存的就不说了,和上篇没什么差别。用户第一次上传是传的tempfile中,确定之后再移到个人文件夹下。


   第一次从MoveTo的时候,以为只要写好目的文件夹名称就可以,但一直报错为找到部分目录,一直奇怪,原来需要加上你传递文件的名称和扩展名。才能移动。


  所以就再取了个名字。



  var scr = Server.MapPath("../Content/TempFile/62231101jw1e3t0apspuoj.jpg");//仅仅是为了测试
var imgname =string.Format("{0:yyyMMdd}",DateTime.Now).Replace("/","")+ DateTime.Now.Ticks.ToString(CultureInfo.InvariantCulture).Substring(7,11)+".jpg";
var scrdestination = Path.Combine(HttpContext.Server.MapPath("../Content/UploadFiles/"), imgname);
FileInfo img=new FileInfo(scr);
if (img.Exists)
{
img.MoveTo(scrdestination);
}

 

 

posted on 2013-09-11 16:39  MikeJia  阅读(2496)  评论(0编辑  收藏  举报

导航