[转载].net mvc 大文件上传 – 无聊的过客博客园.
因客户需要上传大文件,传统的mvc文件上传方法无法满足当前需求。所以哥就只能在网搜现成的列子,找了半天也没有找到好的demo.
大部分多是.net webFrom的例子。都是封装好的控件,顿时郁闷。
在网上虽然没有找到好的例子,但也在找到很好的解决方法那就是使用 swfUpload控件。swfUpload是JavaScript和falsh的合体。网上推荐指数比较高,资料也比较多。
中文api网址:http://leeon.me/upload/other/swfupload.html
1.想看截图。
2.swfUpload比较灵活,可自由扩展,就是需要花时间熟悉。本人花了半天时间才理清楚。官网上也有。net例子也是webFrom的
3.废话少说直接看代码:控制层:
public Guid Swfupload()
{
string uploadsFolder = HttpContext.Server.MapPath(“~/Upload”);
Guid identifier = Guid.NewGuid();
var uploadsPath = Path.Combine(uploadsFolder, identifier.ToString());
var httpfile = Request.Files[“Filedata”];
if (httpfile != null)
{
httpfile.SaveAs(uploadsPath);
}
return identifier;
}
4.显示层可以看官网的例子。还是挺好的。本人结合JQueryUI控件又写了一个例子。主要是替换官网的进度条。
是点击上传时,在对话框里显示上传进度。
@{ ViewBag.Title = "文件上传Demo"; Layout = "~/Views/Shared/_Layout.cshtml"; } @section Head{ <script src="/Scripts/SwfUpload/swfupload.js" type="text/javascript"></script> <script src="/Scripts/SwfUpload/plugins/swfupload.queue.js" type="text/javascript"></script> <script src="/Scripts/SwfUpload/plugins/swfupload.speed.js" type="text/javascript"></script> <script type="text/javascript"> var swfu; window.onload = function () { swfu = new SWFUpload({ upload_url: "/Home/Swfupload", flash_url: "/Scripts/SwfUpload/Flash/swfupload.swf", file_size_limit: "1500 MB", file_types: "*.*", file_types_description: "All Files", file_upload_limit: 0, file_queue_limit: 1, debug: false, // Button settings button_image_url: "/Scripts/SwfUpload/Images/TestImageNoText_65x29.png", button_width: "65", button_height: "29", button_placeholder_id: "spanButtonPlaceHolder", button_text: '<span class="theFont">浏览</span>', button_text_style: ".theFont { font-size: 16; }", button_text_left_padding: 12, button_text_top_padding: 3, file_dialog_complete_handler: function (numFilesSelected, numFilesQueued) { }, file_queued_handler: function (file) { $("#fileName").val(file.name); }, upload_progress_handler: function (file, complete, total) { var value = complete / total * 100; $("#progressbar").progressbar("value", value); $("#CurrentSpeed").html(SWFUpload.speed.formatBPS(file.currentSpeed)); }, upload_success_handler: function (file, data) { alert("文件上传成功"); $("#fileProgress").dialog("close"); } }); $("#btnSubmit").click(function () { if (swfu.getStats().files_queued > 0) { $("#fileProgress").dialog({ modal: true, width: 400, open: function () { $("#progressbar").progressbar({ value: 0 }); swfu.startUpload(); } }); } }); $("#cancelButton").click(function () { swfu.stopUpload(); }); }; </script> } <fieldset> <legend>文件上传Demo</legend> <div> <input type="text" id="fileName" /> <span id="spanButtonPlaceHolder">浏览</span> <button id="btnSubmit"> 上传</button> </div> </fieldset> <div title="文件上传进度" id="fileProgress" style="display: none"> <div id="progressbar"> </div> <button id="cancelButton"> 取消上传</button> 当前上传速度: <span id="CurrentSpeed"></span> </div>