.NET 4.5 的HttpTaskAsyncHandler上传文件

6

我正在尝试学习如何使用新的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");
    }
}

除此之外,尝试使用大型文本文件进行测试。这样结果将是可访问的,但您可以看到文件正在发生的情况。 - stevenrcfox
我在考虑是否需要解析实际请求并查找表单/多部分数据? - superlogical
@superlogical:你应该将评论中的大部分信息移动到实际问题中;它会掩盖代码并阻碍问题的可读性。 - casperOne
你解决了吗?当使用GetBufferlessInputStream时,我遇到了类似的问题,但如果使用InputStream则不存在这些问题。 - Marko
2个回答

0

虽然我没有真正尝试你的代码,但我注意到一件事。你的Response.ContentType = image/gif应该使用BinaryStream而不是常规流,因为你正在处理图像。


响应的ContentType应该是text/plain,因为我正在异步地将“Done”作为响应写入浏览器。 - superlogical

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接