JS+WebService 大文件分片上传代码及解析

在编写前端的过程中,难免会遇到文件上传的问题,当用户要上传较大的文件是,会被服务器端限制,阻止其上传,在ASP.Net中,调整服务器接受文件的大小的配置方法如下:
在ASP中配置Web.config文件的httpRuntime:

<httpRuntime executionTimeout="90" maxRequestLength="40960" useFullyQualifiedRedirectUrl="false"minFreeThreads="8" minLocalRequestFreeThreads="4" appRequestQueueLimit="100" enableVersionHeader="false"/>

其中各参数的作用为:

executionTimeout:表示允许执行请求的最大时间限制,单位为秒 。
maxRequestLength:指示 ASP.NET支持的最大文件上载大小。该限制可用于防止因用户将大量文件传递到该服务器而导致的拒绝服务攻击。指定的大小以 KB 为单位。默认值为 4096KB (4 MB)。
useFullyQualifiedRedirectUr:表示指示客户端重定向是否是完全限定的(采用”http://server/path” 格式,这是某些移动控件所必需的),或者指示是否代之以将相对重定向发送到客户端。如果为True,则所有不是完全限定的重定向都将自动转换为完全限定的格式。false 是默认选项。
minFreeThreads:表示指定允许执行新请求的自由线程的最小数目。ASP.NET为要求附加线程来完成其处理的请求而使指定数目的线程保持自由状态。默认值为 8。
minLocalRequestFreeThreads:表示ASP.NET保持的允许执行新本地请求的自由线程的最小数目。该线程数目是为从本地主机传入的请求而保留的,以防某些请求在其处理期间发出对本地主机的子请求。这避免了可能的因递归重新进入Web 服务器而导致的死锁。
appRequestQueueLimit:表示ASP.NET将为应用程序排队的请求的最大数目。当没有足够的自由线程来处理请求时,将对请求进行排队。当队列超出了该设置中指定的限制时,将通过“503 -服务器太忙”错误信息拒绝传入的请求。 enableVersionHeader:表示指定 ASP.NET是否应输出版本标头。Microsoft Visual Studio 2005 使用该属性来确定当前使用的 ASP.NET版本。对于生产环境,该属性不是必需的,可以禁用。

但是,即使把服务器的配置中的上传文件大小写的够大,又会受到IIS的限制,而且也不能为用户提供安全的服务。那有没有一种方法能解决大文件上传的问题呢?
肯定是有的:分片上传。
分片上传是指将想要上传的文件在前端切割成大小很小的小块,然后再传给服务器,从服务器端再将文件组合成整的文件。
先从前端说起,在分片上传的过程中,前端任务是将文件分片,分片的办法有很多,例如可以使用WebUpLoader提供的上传组件进行分片,也可以用JS与JQ提供的代码进行上传,代码实例如下:

var BYTES_PER_CHUNK = 1024 * 1024; // 每个文件切片大小定为1MB .
var slices;
var totalSlices;

//发送请求
function sendRequest() {
var blob = document.getElementById("yourID").files[0];
var start = 0;
var end;
var index = 0;


// 计算文件切片总数
slices = Math.ceil(blob.size / BYTES_PER_CHUNK);
totalSlices= slices;
while(start < blob.size) {
end = start + BYTES_PER_CHUNK;
if(end > blob.size) {
end = blob.size;
}
uploadFile(blob, index, start, end);
start = end;
index++;
if ( index>=totalSlices )
alert("Complete!!");
}
}

//上传文件
function uploadFile(blob, index, start, end) {
var xhr;
var fd;
var chunk;  
var sliceIndex=blob.name+index;
chunk =blob.slice(start,end);//切割文件

fd = new FormData();
fd.append("FileName", chunk, sliceIndex);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'Server URL', false);//false,同步上传;ture,异步上传
xhr.send(fd);
if((xhr.status >=200 && xhr.status < 300) || xhr.status == 304){
setTimeout("",10);
}else{
uploadFile(blob, index, start, end);
}
}

有了前端,当然少不了在后端的接受与组合,在这里我用ASP.Net为例,说明如何接收与组合文件。

public void RecoveryKPJD()
        {
            HttpContext context = System.Web.HttpContext.Current;
            context.Response.ContentType = "text/plain";
            //如果进行了分片
            if (context.Request.Form.AllKeys.Any(m => m == "chunk"))
            {
                //取得chunk和chunks
                int chunk = Convert.ToInt32(context.Request.Form["chunk"]);//当前分片在上传分片中的顺序(从0开始)
                int chunks = Convert.ToInt32(context.Request.Form["chunks"]);//总分片数
                //根据GUID创建用该GUID命名的临时文件夹
                string folder = Your Path + context.Request["guid"] + "/";
                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);
                //获得上传的分片数据流
                HttpPostedFile file = context.Request.Files[0];
                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)
                {
                    //合并文件
                    ProcessRequest(context.Request["guid"], Path.GetExtension(file.FileName));
                }
            }
            else//没有分片直接保存
            {
                string targetPath = ""; //此处写文件的保存路径
                context.Request.Files[0].SaveAs(targetPath);
            }
        }

   private void ProcessRequest(string guid, string fileExt)
        {
            HttpContext context = System.Web.HttpContext.Current;
            context.Response.ContentType = "text/plain";
            string sourcePath = Path.Combine("Your Path", guid + "/");//源数据文件夹
            string targetPath = Path.Combine("Your Path", Guid.NewGuid() + fileExt);//合并后的文件

            DirectoryInfo dicInfo = new DirectoryInfo(sourcePath);
            if (Directory.Exists(Path.GetDirectoryName(sourcePath)))
            {
                FileInfo[] files = dicInfo.GetFiles();
                foreach (FileInfo file in files.OrderBy(f => int.Parse(f.Name)))
                {
                    FileStream addFile = new FileStream(targetPath, FileMode.AppenFileAccess.Write);
                    BinaryWriter AddWriter = new BinaryWriter(addFile);

                    //获得上传的分片数据流
                    Stream stream = file.Open(FileMode.Open);
                    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();
                }
            }
        }

以上就是服务器接收并合并的C#代码,如果觉得有用,请别忘了给博主点赞哦!

猜你喜欢

转载自blog.csdn.net/wangbingqian_110/article/details/79463031