0

我正在尝试以小块大小将文件复制到 Web 处理程序。当缓冲区相对较大并且总是图像大小时,它可以正常工作。但是我得到块大小的图像失真太小了。

当我再次将相同的字节重新组合在一起时,为什么它会改变?

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);
    
            }
        }
    }
    
4

1 回答 1

0

啊。哑问题。由于我的命名方案是 1、2、3、4、5、6、7、8、9、10,这些文件出现故障。因此,当它达到 10 时,值为 1,10,2,3,4...

var directory = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory + "images");
var files = directory.GetFiles(fileguid + "*").OrderBy(x => x.CreationTime).ToArray();

愚蠢的错误。

于 2013-06-06T16:10:55.807 回答