分片上传文件

分片上传大型文件

页面内容
//引入样式及JS
<link href="~/CSS/webuploader.css" rel="stylesheet" />
<script src="~/JS/webuploader.js"></script>

//页面内容html
<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,
    //$btn = btnObj,
    state = 'pending',
    guploader;
    GUID = WebUploader.Base.guid();

    guploader = WebUploader.create({

        // 不压缩image
        //resize: false,
        //dnd: $("#tuoDiv"),
        // swf文件路径
        swf: '~/CommonJS/FileCommonUI/Uploader.swf',

        // 文件接收服务端。
        server: routeURL,
        duplicate: true,
        // 选择文件的按钮。可选。
        // 内部根据当前运行是创建,可能是input元素,也可能是flash.
        pick: pickStr,
        //fileNumLimit: 'undefined',
        //fileSingleSizeLimit: 'undefined',
        //fileSizeLimit: 'undefined',
        auto: true,
        chunked: true, //分片处理大文件
        chunkSize: 5 * 1024 * 1024,
        threads: 1,
        compress: false, //图片在上传前进行压缩
        fileNumLimit: 300,
        fileSizeLimit: 10000 * 1024 * 1024,    // 200 M
        fileSingleSizeLimit: 10000 * 1024 * 1024,    // 50 M
        formData: { guid: GUID },

    });

    // 当有文件添加进来的时候
    guploader.on('fileQueued', function (file) {
        $list.append('
+ file.id + '" class="item">' + '

' + file.name + '

'
+ '

等待上传...

'
+ '
'
); }); 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 = $('
' + '
' + '
'
+ '
'
).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('
+ response.id + '\', this)" class="del">
'
); ***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"]);//当前分片在上传分片中的顺序(从0开始)
            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));
            //关闭BinaryReader文件阅读器
            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));
                        //关闭BinaryReader文件阅读器
                        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);
}

你可能感兴趣的:(笔记)