.NET 4.5 HttpTaskAsyncHandler上传文件

时间:2011-10-17 16:23:05

标签: c# asp.net .net-4.5

我正在尝试研究如何使用新的asp.net 4.5异步处理程序以及Request.GetBufferlessInputStream来将图像上传到磁盘。这段代码运行,它写出一个文件,但图像已损坏,我不知道为什么。这是我正在使用的代码

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

2 个答案:

答案 0 :(得分:0)

没有真正尝试你的代码我注意到了一件事。你的Response.ContentType = image/gif也不应该是一个BinaryStream而不是常规流,因为它是你正在使用的Image ..?

答案 1 :(得分:0)

现在使用ASP.NET Web Api看起来有一种简单的方法可以解决这个问题!

在此处阅读:http://blogs.msdn.com/b/henrikn/archive/2012/03/01/file-upload-and-asp-net-web-api.aspx

使用其中一个坏男孩MultipartFormDataStreamProvider