2013-06-06 135 views
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); 
    
         } 
        } 
    } 
    

回答

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(); 

愚蠢的錯誤。