大文件上传和下载ASP .NET MVC4

时间:2014-06-01 14:54:52

标签: asp.net-mvc-4 file-upload plupload

任何人都可以使用Custom Control插件在ASP .NET MVC4中使用PlUpload向我提供上传和下载不同类型文件的代码示例。我想为我的任务保存文件,在数据库中使用唯一的ID消息,并且也想要检索它们。这是我尝试上传的代码

服务器端

public ActionResult UploadFiles(string id)
{
for (int i = 0; i < Request.Files.Count; i++)
{
    var file = Request.Files[i];



    file.SaveAs(AppDomain.CurrentDomain.BaseDirectory + "Uploads/" + file.FileName);
}
return Json(new { success = true }, JsonRequestBehavior.AllowGet);
}

用于客户端上传文件的plupload插件代码是

$("#file_attachments").pluploadQueue(
{
    // General settings
    runtimes: 'html5,flash,silverlight',
    url: '/SideMenuBar/UploadFiles',
    max_file_size: '100mb',
    chunk_size: '1mb',
    unique_names: true,

    multipart: true,
    // Specify what files to browse for
    filters: [
        { title: "Image files", extensions: "jpg,gif,png" },
        { title: "Zip files", extensions: "zip" },
        { title: "Rar files", extensions: "rar" },
        { title: "Document files", extensions: "docx,doc,xlx,xlxs,ppt" },

    ],
    // Flash settings
    flash_swf_url: 'Script/lib/plupload/js/plupload.flash.swf',
    // Silverlight settings
    silverlight_xap_url: 'Script/lib/plupload/js/plupload.silverlight.xap',
    // PreInit events, bound before any internal events
    preinit: {
        Init: function (up, info) {
                //alert('[Init]'+ info+ 'Features:'+ up.features);
        },

        UploadFile: function (up, file) {
            //  alert('[UploadFile]', file);
            // You can override settings before the file is uploaded
            up.settings.url = '/SideMenuBar/UploadFiles?id=' + file.id;
            //up.settings.multipart_params = {param1: 'value1', param2: 'value2'};
        }
    },

    // Post init events, bound after the internal events
    init: 
        UploadComplete: function (up, files) {
            // destroy the uploader and init a new one
            up.destroy();
        }
    }
    });

   var uploader = $('#file_attachments').pluploadQueue();
   uploader.bind('FileUploaded', function (upldr, file, object) {

       if (uploader.files.length == (uploader.total.uploaded + uploader.total.failed)) {
           $(".file_upload_cancel").hide();
            $(".file_upload_done").show();
        }
   });
   uploader.bind("FilesAdded", function (up, filesToBeAdded) {
       if (up.files.length > 5) {
           up.files.splice(4, up.files.length - 5);
           showStatus("Only 5 files max are allowed per upload. Extra files removed.", 3000, true);
           return false;
       }
       return true;
   });
    $('.upload_files').click(function (e) {
        e.preventDefault();
        $(".file_up").show();
    });
    $('#new_message_form').submit(function (e) {
        var uploader = $('#file_attachments').pluploadQueue();
        // Files in queue upload them first
        if (uploader.files.length > 0) {
            // When all files are uploaded submit form
            uploader.bind('StateChanged', function () {
                if (uploader.files.length === (uploader.total.uploaded + uploader.total.failed))              {
                    //uncoment next line to submit form after all files are uploaded
                    //$('#new_message_form')[0].submit();
                }
            });
            uploader.start();
        }
        return false;
    });

}

如何解决问题

1 个答案:

答案 0 :(得分:2)

您正在使用名为&#34; chunk&#34;的选项,它将文件按照块的大小进行划分 - 这是一种很好的做法,可以防止错误。

您已使用属性&#34; chunk_size&#34;确定了它。例如:你有一个5mb的文件。上传时,您将拥有5个1mb的部分 - 直到上传完成。然后,你必须把它们放在一起。

我建议您查看this link有关块的更多信息以及如何使其工作。

这是我的一个实现 - 使用MVC 3 - 使用chunk的plupload。 我将发布javascript代码和操作。我认为在你的案例中知道如何实施将是一件好事。

function installFolderFileUploader(action, id, ProfileType, intMaxFilesPermitted, Folder, maxSizeMB) {
var uploaderRuntimes = 'html5, flash, silverlight';

var uploader = new plupload.Uploader({
    runtimes: uploaderRuntimes,
    browse_button: 'imgBtnPhotoUpload',
    url: action,
    flash_swf_url: '/Scripts/Plugins/Moxie.swf',
    silverlight_xap_url: '/Scripts/Plugins/Moxie.xap',
    multipart_params: { 'id': id, 'ProfileType': ProfileType },
    multi_selection: true,
    max_file_count: '5',
    chunk_size: '100KB',
    filters: {
        max_file_size: maxSizeMB + 'MB'
    },
    init: {
        FileUploaded: function (Up, File, Response) {
            var jsonObj = jQuery.parseJSON(Response.response);
            if (jsonObj.success) {
                mountFileUploadFields(jsonObj, Folder, ProfileType);
            }               
        },

        PostInit: function () {
            //meow
            $('#imgBtnPhotoUpload').next().css({ 'top': '0', 'width': '146px', 'height': '28px', 'cursor': 'pointer' });
        },

        FilesAdded: function (up, files) {
            var totalInPage = parseInt($('#dvFileContainer .BeeFileDetails').length);
            if ((up.files.length + totalInPage) > parseInt(intMaxFilesPermitted)) {
                jQuery.facebox({ div: "#dvMaxFilesPermitedError" });

                up.splice();
                up.refresh();

                return false;
            }
            else {
                if (totalInPage >= parseInt(intMaxFilesPermitted)) {
                    jQuery.facebox({ div: "#dvMaxFilesPermitedError" });

                    up.splice();
                    up.refresh();

                    return false;
                }
                else {
                    $('#dvFileList').css('margin-left', '2px');
                    $('#dvFileList').css('font-size', '10px');
                    $('#dvFileList').css('display', 'block');

                    plupload.each(files, function (file) {

                        $('#dvFileList').append('<div>');
                        $('#dvFileList').append('<div style="width:84%;margin-left:30px;float:left;" id="' + file.id + '">' + file.name + ' (' + plupload.formatSize(file.size) + ')<b></b></div>');
                        $('#dvFileList').append('<img class="removeFile" style="margin-top:2px;cursor:pointer;" src="/Content/images/cancel.png" id="' + file.id + '" />');
                        $('#dvFileList').append('</div>');

                        $('.removeFile').on('click', function () {
                            $('#' + file.id).remove();
                            $('img[id=' + file.id + ']').remove();

                            uploader.stop();
                            uploader.splice();
                        });
                    });

                    uploader.start();
                }
            }
        },

        UploadProgress: function (up, file) {
            if (file.percent == 100) {
                $('#' + file.id).remove();
                $('img[id=' + file.id + ']').remove();
            }

            $('#' + file.id + ' b:eq(0)').html('<span> - ' + file.percent + '%</span>');
            $('#' + file.id + ' b:eq(0)').append('<div id="fileUploaded" style="background-color:#0099FF;height:3px;width:' + file.percent + '%";></div>');
        },

        ChunkUploaded: function (up, file, info) {
            var jsonObj = jQuery.parseJSON(info.response);
            if (jsonObj.tempFile != "") {
                uploader.settings.multipart_params.tempFile = jsonObj.tempFile;
            }
            else {
                $('#' + file.id).remove();
                $('img[id=' + file.id + ']').remove();

                var totalInPage = parseInt($('#dvFileContainer .BeeFileDetails').length);
                if (totalInPage > 0)
                    $('.BeeEditFileActions').fadeIn();

                var fileName = uploader.settings.multipart_params.tempFile;
                removeNonUsedFiles(id, fileName, 'File');

                uploader.settings.multipart_params.tempFile = '';

                uploader.stop();
                uploader.splice();
                uploader.refresh();

                jQuery.facebox({ div: "#dvAddFolderFileError" });
            }
        },

        Error: function (up, err) {
            if (err.code != '-500')
                jQuery.facebox({ div: "#dvAddFolderFileError" });
        },
        UploadComplete: function (a, Response) {
            $('.BeeEditFileActions').fadeIn();
            $('#dvFileList').empty();

            uploader.splice();
            uploader.refresh();
        }
    }
});

uploader.init();

}

动作:

[AllowAnonymous]
    [HttpPost]
    public JsonResult UploadFolderFile(string id, Domain.Profile.TypeProfile ProfileType, string tempFile, string name, int? chunk, int? chunks)
    {
        String strTempFile = string.Empty;
        String strSaveLocation = string.Empty;
        try
        {
            var fileData = Request.Files[0];
            chunk = chunk ?? 0;

            String strExtension = Path.GetExtension(name).ToLower();
            Models.Identity.CustomIdentity objUser = new Models.Identity.CustomIdentity(System.Web.Security.FormsAuthentication.Decrypt(id));
            DB.CompanyNetworkDB objCompanyDB = new DB.CompanyNetworkDB();
            Int32 intMaxFileSize = objCompanyDB.getFileInFolderMaxSize(objUser.CompanyNetworkID) * 1024 * 1024;

            if (objUser != null && objUser.IsAuthenticated && fileData.ContentLength <= intMaxFileSize)
            {
                ////Get upload file.
                String strSaveLocationURL = Domain.Profile.getUploadItemsFolder(objUser.CompanyNetworkID, ProfileType, Domain.Profile.UploadType.Folder);
                strSaveLocationURL += "temp/";
                strSaveLocation = Server.MapPath(strSaveLocationURL);
                strTempFile = string.IsNullOrEmpty(tempFile) ? DateTime.Now.Ticks.ToString() + strExtension : tempFile;

                long fileSize = 0;
                using (var fs = new FileStream(Path.Combine(strSaveLocation, strTempFile), chunk == 0 ? FileMode.Create : FileMode.Append))
                {
                    var buffer = new byte[fileData.InputStream.Length];
                    fileData.InputStream.Read(buffer, 0, buffer.Length);

                    fs.Write(buffer, 0, buffer.Length);
                    fileSize = fs.Length;
                }
                if (fileSize <= intMaxFileSize)
                {
                    if (chunk == chunks - 1)
                    {
                        return Json(new { success = true, OriginalFileName = Path.GetFileName(name), ServerFileName = strTempFile, SizeMB = fileSize });
                    }
                    else
                    {
                        return Json(new { success = true, tempFile = strTempFile });
                    }
                }
                else
                {
                    return Json(new { success = false });
                }
            }
            else
            {
                return Json(new { success = false });
            }
        }
        catch (ArgumentOutOfRangeException)
        {
            System.IO.File.Delete(Path.Combine(strSaveLocation, strTempFile));

            return Json(new { success = false, erro = "canceled" });
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }
    }

我认为这可能会有所帮助。