0
我试图将文件复制到小块大小的web处理程序。当缓冲区相对较大时总是可以正常工作,并且总是处于图像大小的时候。但是我得到的图像块大小变形太小。小字节[]块导致图像损坏
为什么,当我“M重新把相同的字节重新走到一起变化?
OpenFileDialog o = new OpenFileDialog();
o.ShowDialog();
using (WebClient webClient = new WebClient())
{
int index = 0;
var tmpName = Guid.NewGuid().ToString();
const int chunkSize = 10*1024;
webClient.Headers.Add("Filename", "");
using (var file = o.OpenFile())
{
int bytesRead;
//Using ChunkSize will give image distortion. But file.length works. So does dividing by 10 to result in 10 chunks. Why?
byte[] buffer = new byte[file.Length/10];
int position = 0;
while (position < file.Length)
{
if (position + buffer.Length > file.Length)
{
buffer = new byte[file.Length - position];
}
bytesRead = file.Read(buffer, 0, buffer.Length);
position += bytesRead;
var fileName = string.Format("{0}.{1}.{2}", tmpName, index, o.SafeFileName);
webClient.Headers["Filename"] = fileName;
//webClient.Headers["blockSize"] = buffer.Length.ToString();
webClient.UploadData("http://localhost:49815/FileUpload.ashx", buffer);
index++;
}
}
var values = new NameValueCollection();
values.Add("Filename", string.Format("{0}.{1}", tmpName, o.SafeFileName));
values.Add("Complete", "true");
webClient.Headers.Clear();
webClient.UploadValues("http://localhost:49815/FileUpload.ashx", values);
}
我测试
- 如果我不传递给块到fileupload.ashx,并把这些块重新放回到客户端应用程序中,它工作正常。
- 文件大小与服务器端完全匹配
同样的问题发生时将分解的文件保存到相同的位置。所以HTTP与它无关。
private void CombineFiles(string filename) { var fileguid = filename.Substring(0, filename.IndexOf(".") + 1); var shortFileName = filename.Replace(fileguid, ""); var files = Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory + "images", fileguid + "*"); using (var filestream = File.Create(AppDomain.CurrentDomain.BaseDirectory + "images/" + shortFileName)) { foreach (string file in files) { var fileBuffer = File.ReadAllBytes(file); filestream.Write(fileBuffer, 0, fileBuffer.Length); File.Delete(file); } } }