1. 程式人生 > >webuploader分片上傳大檔案

webuploader分片上傳大檔案

html:

<style>
    .wu-example {
        position: relative;
        padding: 45px 15px 15px;
        margin: 15px 0;
        background-color: #fafafa;
        box-shadow: inset 0 3px 6px rgba(0, 0, 0, .05);
        border-color: #e5e5e5 #eee #eee;
        border-style: solid;
        border-width
: 1px 0
; }
#picker { display: inline-block; line-height: 1.428571429; vertical-align: middle; margin: 0 12px 0 0; } #picker .webuploader-pick { padding: 6px 12px; display: block; }
</style> @Styles.Render("~/Content/css") @Scripts.Render("~/bundles/jquery") <link
rel="stylesheet" type="text/css" href="~/Scripts/webuploader/webuploader.css">
<script type="text/javascript" src="~/Areas/DataCenter/Content/layer/layer.js"></script> <script type="text/javascript" src="~/Areas/DataCenter/Content/js/dcommon.js"></script> <div id="uploader" class="wu-example"
>
<!--用來存放檔案資訊--> <div id="thelist" class="uploader-list"></div> <div class="btns"> <div id="picker">選擇檔案</div> <button id="ctlBtn" class="btn btn-default btn-sm">開始上傳</button> <button id="btnReset" class="btn btn-default btn-sm">重置</button> </div> </div> <script type="text/javascript" src="~/Scripts/webuploader/webuploader.js"></script> <script> $(document).ready(function () { var GUID = WebUploader.Base.guid(); var uploader = WebUploader.create({ // swf檔案路徑 swf: '/scripts/webuploader/Uploader.swf', // 檔案接收服務端。 server: '/dbc/Uptest', // 選擇檔案的按鈕。可選。 // 內部根據當前執行是建立,可能是input元素,也可能是flash. pick: '#picker', //禁用拖拽上傳 disableGlobalDnd: true, // 不壓縮image, 預設如果是jpeg,檔案上傳前會壓縮一把再上傳! resize: false, //分片 chunked: true, //每片大小 2M chunkSize: 2097152, //單片失敗後重試次數 chunkRetry: 5, //上傳併發執行緒數 threads: 1, //可上傳檔案數量 fileNumLimit: 1, //圖片上傳之前不壓縮 compress: false, formData: { guid: GUID } }); // 當有檔案被新增進佇列的時候 uploader.on('fileQueued', function (file) { $('#thelist').append('<div id="' + file.id + '" class="item">' + '<h4 class="info">' + file.name + '</h4>' + '<p class="state">等待上傳...</p>' + '</div>'); }); // 檔案上傳過程中建立進度條實時顯示。 uploader.on('uploadProgress', function (file, percentage) { var $li = $('#' + file.id), $percent = $li.find('.progress .progress-bar'); // 避免重複建立 if (!$percent.length) { $percent = $('<div class="progress progress-striped active">' + '<div class="progress-bar" role="progressbar" style="width: 0%">' + '</div>' + '</div>').appendTo($li).find('.progress-bar'); } $li.find('p.state').text('上傳中'); $percent.css('width', percentage * 100 + '%'); }); uploader.on('uploadSuccess', function (file, response) { accecpResult(response, function () { $('#' + file.id).find('p.state').html('已上傳:<a href=/dbc/getfile?url={0} target=_blank>{0}</a>'.format(response.data)); }) }); uploader.on('uploadError', function (file) { $('#' + file.id).find('p.state').text('上傳出錯'); }); uploader.on('uploadComplete', function (file) { $('#' + file.id).find('.progress').fadeOut(); }); $('#ctlBtn').on('click', function () { uploader.upload(); }); $('#btnReset').on('click', function () { uploader.reset(); $('#thelist').html(''); }); }) </script>

控制器方法:

 public JsonResult Uptest()
        {
            string dirname = "pic";
            string path = System.Configuration.ConfigurationManager.AppSettings["UploadPath"];
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            if (!Directory.Exists(path + "/" + dirname))
            {
                Directory.CreateDirectory(path + "/" + dirname);
            }

            string guid = Request.Form["guid"];

            string id = Request.Form["id"];
            string filename = Request.Form["name"];
            int chunks = 0, chunk = 0;
            if (Request.Form["chunks"] != null)
            {
                chunks = int.Parse(Request.Form["chunks"]);
                chunk = int.Parse(Request.Form["chunk"]);
            }

            string ext = Path.GetExtension(filename);
            string savefile = DateTime.Now.ToFileTime() + ext;
            string url = "/" + dirname + "/" + savefile;

            HttpPostedFileBase file = Request.Files[0];
            if (chunks == 0)
            {
                //沒分片
                try
                {
                    file.SaveAs(path + url);
                    return Json(Dcampus.Areas.DataCenter.DAL.Common.Msg(Common.AjaxStatu.ok, url));
                }
                catch (Exception e)
                {
                    return Json(Dcampus.Areas.DataCenter.DAL.Common.Msg(Common.AjaxStatu.err, e.Message));
                }
            }
            else
            {
                try
                {
                    string gurl = path + "/" + dirname + "/" + guid;
                    string guidurl = gurl + "/" + id;
                    if (!Directory.Exists(guidurl))
                    {
                        Directory.CreateDirectory(guidurl);
                    }
                    string f_index = chunk.ToString() + Path.GetExtension(filename);
                    file.SaveAs(guidurl + "/" + f_index);

                    if (chunk == chunks - 1)
                    {
                        string targetPath = path + url;
                        for (int i = 0; i < chunks; i++)
                        {
                            using (FileStream addFile = new FileStream(targetPath, FileMode.Append, FileAccess.Write))
                            {
                                BinaryWriter bWriter = new BinaryWriter(addFile);
                                FileInfo fi = new FileInfo(guidurl + "/" + i + Path.GetExtension(filename));
                                Stream stream = fi.Open(FileMode.Open);
                                BinaryReader tempReader = new BinaryReader(stream);
                                bWriter.Write(tempReader.ReadBytes((int)stream.Length));
                                tempReader.Close();
                                stream.Close();
                            }
                        }
                        DeleteFolder(gurl);
                        return Json(Dcampus.Areas.DataCenter.DAL.Common.Msg(Common.AjaxStatu.ok, url));
                    }
                    else
                    {
                        return Json(Dcampus.Areas.DataCenter.DAL.Common.Msg(Common.AjaxStatu.ok));
                    }
                }
                catch (Exception e)
                {
                    return Json(Dcampus.Areas.DataCenter.DAL.Common.Msg(Common.AjaxStatu.err, e.Message));
                }
            }
        }

        private static void DeleteFolder(string strPath)
        {
            //刪除這個目錄下的所有子目錄
            if (Directory.GetDirectories(strPath).Length > 0)
            {
                foreach (string fl in Directory.GetDirectories(strPath))
                {
                    Directory.Delete(fl, true);
                }
            }
            //刪除這個目錄下的所有檔案
            if (Directory.GetFiles(strPath).Length > 0)
            {
                foreach (string f in Directory.GetFiles(strPath))
                {
                    System.IO.File.Delete(f);
                }
            }
            Directory.Delete(strPath, true);
        }

        public FileResult GetFile(string url)
        {
            var path = System.Configuration.ConfigurationManager.AppSettings["UploadPath"] + url;
            var filename = Path.GetFileName(path);
            return File(path, "application/octet-stream", filename);
        }