ASP.NET 使用 plupload 上传大文件时出现“blob”文件的Bug

最近在一个ASP.NET 项目中使用了plupload 来上传文件,结果几天后客户发邮件说上传的文件不对,说是文件无法打开

在进入系统进行查看后发现上传的文件竟然没有后缀,经过一番测试发现如果文件上传的太大就可能出现该问题
 
随后在google上进行搜索才知道当使用html5上传大文件时就有可能出现该问题
好在Plupload官方论坛上给出了解决方案,其实就是将大文件分批写入到同一个文件中
这样就不会受IIS或web.config的最大文件大小限制了
 
1.在js中添加事件
var plupload=$("#uploader").plupload({
//解决分块上传时文件名为"blob"的bug
init:{
BeforeUpload:function(up, file){
// Called right before the upload for a given file starts, can be used to cancel it if required
up.settings.multipart_params ={
filename: file.name
};
},
}
});
2.后台处理文件时使用参数"filename"而不是上传的文件名
  /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="context"></param>
        public void UploadFile(HttpContext context)
        {
            if (context.Request.Files.Count <= 0) return;

            context.Response.CacheControl = "no-cache";

            string s_rpath = "E:website	emp";

            //是否是分块上传
            bool isChunk = false;

            //上传文件路径
            string filepath = string.Empty;

            FileStream fs = null;

            //字节
            Byte[] buffer = null;

            //需要上传的文件
            HttpPostedFile httpUploadFile = null;

            //分块上传的文件名,结合js用于解决使用分块上传时当前文件名为"blob"的bug
            string filename = context.Request["filename"];

            //存在块参数
            if (!string.IsNullOrEmpty(context.Request.Params["chunk"]))
            {
                int chunk_number = 0;
                int.TryParse(context.Request.Params["chunk"], out chunk_number);
                isChunk = chunk_number > 0;//分块上传,第一块为0
            }

            try
            {
                for (int i = 0; i < context.Request.Files.Count; i++)
                {
                    #region 上传文件
                    //文件列表
                    httpUploadFile = context.Request.Files[i];

                    //块文件名不存在则使用当前文件的文件名
                    if (string.IsNullOrEmpty(filename) || filename.Length <= 0)
                        filename = httpUploadFile.FileName;

                    filepath = System.IO.Path.Combine(s_rpath, filename);

                    //对文件流进行存储 
                    //如果是块上传则写入文件否则创建文件
                    fs = new FileStream(filepath, isChunk ? FileMode.OpenOrCreate : FileMode.Append);
                    buffer = new Byte[httpUploadFile.InputStream.Length];
                    httpUploadFile.InputStream.Read(buffer, 0, buffer.Length);
                    fs.Write(buffer, 0, buffer.Length);
                    fs.Close();
                    #endregion
                }
            }
            catch (Exception ex)
            {
                context.Response.Write("error:" + ex.ToString());
            }
        }
 
有图有真相:
 
参考:

关于plupload的使用心得

ps:

为知笔记恶心的强制收费导致非常的不爽

所以准备把未上传到博客的为知笔记文章陆续上传

原文地址:https://www.cnblogs.com/huangtailang/p/7263528.html