我正在实现一个MVC4 + WebAPI版本的BluImp jQuery文件上传一切都适用于我最初的尝试,但我试图确保在下载非常大的文件(~2GB)时最好地使用内存.
我已经阅读了Filip Woj关于PushStreamContent的文章并尽可能地实现它(删除异步部分 - 也许这就是问题?).当我运行测试并观察TaskManager时,我没有看到明显不同的内存使用情况,我试图理解响应如何处理之间的差异.
这是我的StreamContent版本:
private HttpResponseMessage DownloadContentNonChunked()
{
var filename = HttpContext.Current.Request["f"];
var filePath = _storageRoot + filename;
if (File.Exists(filePath))
{
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new StreamContent(new FileStream(filePath, FileMode.Open, FileAccess.Read));
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = filename
};
return response;
}
return ControllerContext.Request.CreateErrorResponse(HttpStatusCode.NotFound, "");
}
Run Code Online (Sandbox Code Playgroud)
这是我的PushStreamContent版本:
public class FileDownloadStream
{
private readonly string _filename;
public FileDownloadStream(string filePath)
{
_filename = filePath;
}
public …Run Code Online (Sandbox Code Playgroud) 我有以下angularjs代码:
$scope.search = function() {
creatorService.search($scope.model).then(function(data) {
saveAs(new Blob([data], { type: "application/octet-stream'" }), 'testfile.zip');
});
};
Run Code Online (Sandbox Code Playgroud)
(也使用fileSaver.js)
然后在我的webapi2方面采用以下方法:
public HttpResponseMessage Post(Object parameters)
{
var streamContent = new PushStreamContent((outputStream, httpContext, transportContent) =>
{
try
{
using (var zip = new ZipFile())
{
zip.AddEntry("test.txt", "test data");
zip.Save(outputStream);
}
}
finally
{
outputStream.Close();
}
});
streamContent.Headers.ContentType = new MediaTypeHeaderValue("application/zip");
streamContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = "test.zip"
};
var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = streamContent
};
return response;
} …Run Code Online (Sandbox Code Playgroud)