我正在使用ajax javascript从客户端上传文件,当收到所有块时,我将其拆分为块并在服务器中加入它们。但问题是,即使原始文件和上传的文件大小相同,但两者却不同。我的意思是当我查看与视频文件不同和相同的 gif 文件时。客户端代码
var xhr = new XMLHttpRequest();
var tempBlob = blob;
var blobOrFile = tempBlob.slice(fileDataStart, fileDataSent);
xhr.open('POST', '/Portfolio/UploadBinaryFiles', false);
xhr.setRequestHeader("Cache-Control", "no-cache");
xhr.setRequestHeader("X-File-Name", fileName);
xhr.setRequestHeader("X-File-Size", fileSize);
xhr.setRequestHeader("X-File-BytesSent", fileDataSent);
xhr.setRequestHeader("X-File-SplitCounter", fileSplitCounter);
xhr.setRequestHeader("Content-Type", "multipart/form-data");
xhr.send(blobOrFile);
服务器端代码加入
FileStream fsSource = new FileStream(FileOutputPath, FileMode.Append);
// Loop through all the files with the *.part extension in the folder
foreach (FileInfo fiPart in diSource.GetFiles(@"*.part"))
{
// Create a byte array of the content of the current file
Byte[] bytePart = System.IO.File.ReadAllBytes(fiPart.FullName);
// Write the bytes to the reconstructed file
fsSource.Write(bytePart, 0, bytePart.Length);
}
在服务器中保存拆分文件
// Read input stream from request
byte[] buffer = new byte[Request.InputStream.Length];
int offset = 0;
int cnt = 0;
while ((cnt = Request.InputStream.Read(buffer, offset, 10)) > 0)
{
offset += cnt;
}
// Save file
using (FileStream fs = new FileStream(fullNameNoExt, FileMode.Create))
{
fs.Write(buffer, 0, buffer.Length);
fs.Flush();
}