2011-10-17 20 views
6

Tôi đang cố gắng tìm hiểu cách sử dụng trình xử lý async asp.net 4.5 mới cũng như Request.GetBufferlessInputStream để ghi ảnh tải lên đĩa. Mã này chạy và nó viết một tệp nhưng hình ảnh bị hỏng và tôi không chắc chắn tại sao. Đây là mã tôi đang sử dụng.NET 4.5 HttpTaskAsyncHandler tải lên một tệp

public class UploadHandler : HttpTaskAsyncHandler 
{ 
    public override Task ProcessRequestAsync(HttpContext context) 
    { 
     // Gets a Stream object that can be used to read the 
     // incoming HTTP entity body, optionally disabling the 
     // request-length limit that is set in the MaxRequestLength property. 

     // This method provides an alternative to using the 
     // InputStream property. The InputStream property waits until the 
     // whole request has been received before it returns a Stream object. 
     // In contrast, the GetBufferlessInputStream method returns 
     // the Stream object immediately. 
     // You can use the method to begin processing the 
     // entity body before the complete contents of the 
     // body have been received. 
     // The entity body (or as much of it as you request and has 
     // been received) is returned only when you use the object that 
     // is returned by this method to read the stream, by calling 
     // methods such as the Read method. You use parameters of the 
     // Read method to specify how much of the entity body to read. 

     // This method can be useful if the request is uploading a 
     // large file and you want to begin accessing the file contents 
     // before the upload is finished. 
     // However, you should only use this method for scenarios where 
     // you want to take over all processing of the entity body. 
     // This means that you cannot use this method from an .aspx page, 
     // because by the time an .aspx page runs, the entity body 
     // has already been read. 

     using (Stream input = context.Request.GetBufferlessInputStream(true)) 
     using (var file = new FileStream("C:\\myfile.jpg", FileMode.Create, 
      FileAccess.Write, FileShare.Write)) 
     { 
      input.CopyTo(file); 
     } 

     context.Response.ContentType = "text/plain"; 
     return context.Response.Output.WriteAsync("Done"); 
    } 
} 
+1

Làm thế nào là nó bị hỏng? – Amy

+0

Hơn nữa ở trên, hãy thử bằng một tệp văn bản lớn. theo cách đó, kết quả sẽ có thể truy cập được nhưng bạn có thể thấy những gì đang xảy ra với tệp. – stevenrcfox

+0

Tôi nghĩ rằng tôi sẽ phải phân tích Yêu cầu thực tế và tìm kiếm dữ liệu biểu mẫu/đa phần? – superlogical

Trả lời

0

không thực sự cố gắng mã của bạn ra tôi nhận thấy một điều. Không nên Response.ContentType = image/gif của bạn cũng nên dòng là một BinaryStream thay vì một dòng thường xuyên vì nó là một hình ảnh mà bạn đang làm việc với ..?

+0

Response.ContentType phải là văn bản/đơn giản vì tôi viết không đồng bộ "Đã hoàn thành" làm phản hồi cho trình duyệt. – superlogical