【问题标题】:Small byte[] chunks cause Image corruption小字节 [] 块导致图像损坏
【发布时间】:2013-06-02 03:03:00
【问题描述】:

我正在尝试以小块大小将文件复制到 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);
    
            }
        }
    }
    

【问题讨论】:

    标签: c# asp.net stream .net


    【解决方案1】:

    呃。哑问题。因为我的命名方案是 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();
    

    愚蠢的错误。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-29
      • 2016-09-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-23
      • 2021-05-30
      • 1970-01-01
      相关资源
      最近更新 更多