分片上传大型文件
页面内容
<link href="~/CSS/webuploader.css" rel="stylesheet" />
<script src="~/JS/webuploader.js"></script>
<div class="wu-example col-sm-10">
<div id="thelist" class="uploader-list"></div>
<div class="btns" style="margin-top:10px;margin-bottom:10px">
<div id="picker" style="float:left;">选择文件</div>
</div>
</div>
Js内容
$(function () {
createUploadObj($('#thelist'), $('#btns'), '#picker', '/DataVisualization/SaveDataVisualizationFile');
thelistObj = $('#thelist');
});
function createUploadObj(listObj, btnObj, pickStr, routeURL) {
var $ = jQuery,
$list = listObj,
state = 'pending',
guploader;
GUID = WebUploader.Base.guid();
guploader = WebUploader.create({
swf: '~/CommonJS/FileCommonUI/Uploader.swf',
server: routeURL,
duplicate: true,
pick: pickStr,
auto: true,
chunked: true,
chunkSize: 5 * 1024 * 1024,
threads: 1,
compress: false,
fileNumLimit: 300,
fileSizeLimit: 10000 * 1024 * 1024,
fileSingleSizeLimit: 10000 * 1024 * 1024,
formData: { guid: GUID },
});
guploader.on('fileQueued', function (file) {
$list.append('<div id="' + file.id + '" class="item">' +
'<h4 class="info">' + file.name + '</h4>' +
'<p class="state">等待上传...</p>' +
'</div>');
});
guploader.on('uploadBeforeSend', function (object, data, header) {
data = $.extend(data, {
});
});
guploader.on('uploadProgress', function (file, percentage) {
parent.$("#MainFrame").find("#loading_background").show();
parent.$("#MainFrame").find("#loading_manage").show();
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 + '%');
if (percentage == 1) {
$li.find('p.state').text('正在合并,请稍候!');
}
});
guploader.on('uploadSuccess', function (file, response) {
$('#' + file.id).find('h4.info').append('<div οnclick="deleteFile(\'' + response.id + '\', this)" class="del"></div>');
***response上传后的内容返回***
$('#' + file.id).find('p.state').text('');
if ($list.children("div").length > 1) {
$list.children("div").eq(0).remove();
}
parent.$("#MainFrame").find("#loading_background").hide();
parent.$("#MainFrame").find("#loading_manage").hide();
});
guploader.on('uploadError', function (file) {
$('#' + file.id).find('p.state').text('上传出错');
});
guploader.on('uploadComplete', function (file) {
$('#' + file.id).find('.progress').fadeOut();
});
guploader.on('all', function (type) {
if (type === 'startUpload') {
state = 'uploading';
} else if (type === 'stopUpload') {
state = 'paused';
} else if (type === 'uploadFinished') {
state = 'done';
guploader.reset();
}
});
}
function deleteFile(fileId, deleteObj) {
}
后台接收上传文件
public ActionResult SaveDataVisualizationFile(HttpPostedFileBase file, string dataVisualizationTabID,string dimension)
{
using (ApplicationDbContext aDb = new ApplicationDbContext())
{
string tempId = string.Empty;
string filePath = string.Empty;
string fileName = string.Empty;
HttpContextWrapper context = new HttpContextWrapper(System.Web.HttpContext.Current);
context.Response.ContentType = "text/plain";
if (context.Request.Form.AllKeys.Any(m => m == "chunk"))
{
int chunk = Convert.ToInt32(context.Request.Form["chunk"]);
int chunks = Convert.ToInt32(context.Request.Form["chunks"]);
string tempDictory = file.FileName.Substring(0, file.FileName.LastIndexOf('.'));
string folder = Path.Combine(HttpRuntime.AppDomainAppPath, @"DataVisualization\" + dataVisualizationTabID + @"\" + tempDictory + @"\");
string path = folder + chunk;
if (!Directory.Exists(Path.GetDirectoryName(folder)))
{
Directory.CreateDirectory(folder);
}
FileStream addFile = new FileStream(path, FileMode.Append, FileAccess.Write);
BinaryWriter AddWriter = new BinaryWriter(addFile);
Stream stream = file.InputStream;
BinaryReader TempReader = new BinaryReader(stream);
AddWriter.Write(TempReader.ReadBytes((int)stream.Length));
TempReader.Close();
stream.Close();
AddWriter.Close();
addFile.Close();
TempReader.Dispose();
stream.Dispose();
AddWriter.Dispose();
addFile.Dispose();
if (chunk == chunks - 1)
{
string targetPath = Path.Combine(HttpRuntime.AppDomainAppPath, @"DataVisualization\" + dataVisualizationTabID + @"\", file.FileName);
string fileUrl = @"../../DataVisualization/" + dataVisualizationTabID + @"/" + file.FileName;
DirectoryInfo dicInfo = new DirectoryInfo(folder);
if (Directory.Exists(Path.GetDirectoryName(folder)))
{
FileInfo[] files = dicInfo.GetFiles();
foreach (FileInfo file1 in files.OrderBy(f => int.Parse(f.Name)))
{
FileStream addFile1 = new FileStream(targetPath, FileMode.Append, FileAccess.Write);
BinaryWriter AddWriter1 = new BinaryWriter(addFile1);
Stream stream1 = file1.Open(FileMode.Open);
BinaryReader TempReader1 = new BinaryReader(stream1);
AddWriter1.Write(TempReader1.ReadBytes((int)stream1.Length));
TempReader1.Close();
stream1.Close();
AddWriter1.Close();
addFile1.Close();
TempReader1.Dispose();
stream1.Dispose();
AddWriter1.Dispose();
addFile1.Dispose();
}
DeleteFolder(folder);
}
filePath = targetPath;
fileName = file.FileName;
}
else
{
return Content("");
}
}
else
{
string localPath = Path.Combine(HttpRuntime.AppDomainAppPath, @"DataVisualization\" + dataVisualizationTabID);
if (Request.Files.Count == 0)
{
return Json(new { jsonrpc = 2.0, error = new { code = 102, message = "保存失败" }, id = dataVisualizationTabID });
}
string fileUrl = @"../../DataVisualization/" + dataVisualizationTabID + @"/" + file.FileName;
string ex = Path.GetExtension(file.FileName);
if (!System.IO.Directory.Exists(localPath))
{
System.IO.Directory.CreateDirectory(localPath);
}
string physicalPath = Path.Combine(localPath, file.FileName);
tempId = dataVisualizationUpload.EntityID.ToString();
filePath = physicalPath;
fileName = file.FileName;
file.SaveAs(physicalPath);
}
}
}
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);
}