Asp.net mvc 4 大型文件上载和下载ASP.NET MVC4
有谁能给我举个例子,通过使用Asp.net mvc 4 大型文件上载和下载ASP.NET MVC4,asp.net-mvc-4,file-upload,plupload,Asp.net Mvc 4,File Upload,Plupload,有谁能给我举个例子,通过使用PlUpload插件在ASP.NETMVC4中使用Custom Control上传和下载不同类型的文件。我想为我的任务保存文件,在数据库中保存具有唯一ID的消息,并想检索它们。这是我试图上传的代码 服务器端 public ActionResult UploadFiles(string id) { for (int i = 0; i < Request.Files.Count; i++) { var file = Request.Files[i];
PlUpload
插件在ASP
.NET
MVC4
中使用Custom Control
上传和下载不同类型的文件。我想为我的任务保存文件,在数据库中保存具有唯一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);
}
}
如何解决问题您正在使用一个名为“chunk”的选项,该选项将您的文件按chunk的大小进行分割-这是一个很好的做法,可以防止出现错误 您已使用属性“chunk\u size”确定它。例如:您有一个5mb的文件。当你上传时,你将拥有1mb的5部分,直到上传完成。然后,你必须把它们放在一起 我建议您了解更多关于chunk以及如何使其工作的信息 下面是我的一个实现示例—使用MVC 3—plupload with chunk。 我将发布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();
函数installFolderFileUploader(操作、id、配置文件类型、允许的IntMaxFiles、文件夹、maxSizeMB){
var uploaderRuntimes='html5、flash、silverlight';
var uploader=新的plupload.uploader({
运行时:上传时间,
浏览按钮:“imgBtnPhotoUpload”,
url:action,
flash_swf_url:“/Scripts/Plugins/Moxie.swf”,
silverlight_xap_url:“/Scripts/Plugins/Moxie.xap”,
多部分参数:{'id':id,'ProfileType':ProfileType},
多重选择:正确,
最大文件计数:“5”,
块大小:“100KB”,
过滤器:{
最大文件大小:maxSizeMB+'MB'
},
初始化:{
上传文件:功能(上传、文件、响应){
var jsonObj=jQuery.parseJSON(Response.Response);
if(jsonObj.success){
mountFileUploadFields(jsonObj、文件夹、ProfileType);
}
},
PostInit:函数(){
//喵喵
$('imgBtnPhotoUpload').next().css({'top':'0','width':'146px','height':'28px','cursor':'pointer'});
},
添加文件:函数(向上,文件){
var totalInPage=parseInt($('#dvFileContainer.BeeFileDetails').length);
如果((up.files.length+totalInPage)>parseInt(允许使用intmaxfiles)){
facebox({div:#dvmaxfilesportederror});
向上拼接();
up.refresh();
返回false;
}
否则{
如果(totalInPage>=parseInt(允许使用IntMaxFiles)){
facebox({div:#dvmaxfilesportederror});
向上拼接();
up.refresh();
返回false;
}
否则{
$('#dvFileList').css('margin-left','2px');
$('#dvFileList').css('font-size','10px');
$('#dvFileList').css('display','block');
plupload.each(文件、函数(文件){
$('#dvFileList')。追加('');
$('#dvFileList').append('+file.name+'('+plupload.formatSize(file.size)+'));
$('#dvFileList')。追加('');
$('#dvFileList')。追加('');
$('.removeFile')。在('click',函数(){
$('#'+file.id).remove();
$('img[id='+file.id+']')。删除();
uploader.stop();
uploader.splice();
});
});
uploader.start();
}
}
},
上载进度:函数(向上,文件){
如果(file.percent==100){
$('#'+file.id).remove();
$('img[id='+file.id+']')。删除();
}
$('#'+file.id+'b:eq(0)').html('-'+file.percent+'%');
$('#'+file.id+'b:eq(0)')。追加('';
},
ChunkUpload:函数(up、file、info){
var jsonObj=jQuery.parseJSON(info.response);
if(jsonObj.tempFile!=“”){
uploader.settings.multipart_params.tempFile=jsonObj.tempFile;
}
否则{
$('#'+file.id).remove();
$('img[id='+file.id+']')。删除();
var totalInPage=parseInt($('#dvFileContainer.BeeFileDetails').length);
如果(总页面>0)
$('.BeeEditFileActions').fadeIn();
var fileName=uploader.settings.multipart_params.tempFile;
删除未删除的文件(id、文件名、“文件”);
uploader.settings.multipart_params.tempFile='';
uploader.stop();
uploader.splice();
uploader.refresh();
facebox({div:#dvAddFolderFileError});
}
},
错误:函数(向上,错误){
如果(错误代码!='-500')
facebox({div:#dvAddFolderFileError});
},
上传完成:功能(a,响应){
$('.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);
}
}
[AllowAnonymous]
[HttpPost]
public JsonResult UploadFolderFile(字符串id,Domain.Profile.TypeProfile ProfileType,字符串tempFile,字符串名称,int?chunk,int?chunks)
{
String strTempFile=String.Empty;
String strSaveLocation=String.Empty;
尝试
{
var fileData=Request.Files[0];
chunk=chunk×0;
String strExtension=Path.GetExtension(name.ToLower();
Models.Identity.CustomIdentity对象
[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);
}
}