我的 Web API 方法返回单个文件或包含多个文件的 zip 文件。这是 Web API 实现。
public HttpResponseMessage Download([FromUri] List<string> fileNames)
{
try
{
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
if (fileNames.Count > 1)
{
List<string> filePaths = new List<string>();
MemoryStream memoryStreamOfFile = new MemoryStream();
using (ZipFile zip = new ZipFile())
{
foreach (var fileName in fileNames)
{
zip.AddFile(HttpRuntime.AppDomainAppPath + @"\Uploaded\" + fileName);
}
zip.Save(memoryStreamOfFile);
memoryStreamOfFile.Seek(0, SeekOrigin.Begin);
result.Content = new StreamContent(memoryStreamOfFile);
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
result.Content.Headers.ContentDisposition.FileName = "files.zip";
result.Content.Headers.ContentType =
new MediaTypeHeaderValue("application/octet-stream");
return result;
}
}
if (!string.IsNullOrEmpty(fileNames[0]))
{
string filePath = HttpRuntime.AppDomainAppPath + @"\Uploaded\" + fileNames[0];
var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
result.Content = new StreamContent(stream);
result.Content.Headers.ContentType =
new MediaTypeHeaderValue("application/octet-stream");
return result;
}
return this.Request.CreateResponse(HttpStatusCode.NotFound, "File not found.");
}
catch (Exception ex)
{
return this.Request.CreateResponse(HttpStatusCode.InternalServerError, ex);
}
}
此方法运行良好,我敢肯定,因为当我通过 Google Chrome 扩展“Advanced Rest Client”请求此方法时,文件已下载并运行良好。
但是当我通过 Angularjs 服务调用请求此方法时,文件无法打开。图像文件给我以下错误
以下为 PDF
和下面的 zip
来自 Advance Rest Client行为是预期的,但不是 Angularjs。 以下是我的 Angular 代码
"download": {
method: "GET",
url: "api/files/Download/",
params: { fileNames: "@fileNames" },
responseType: "arraybuffer",
headers: {
'Content-Type': "application/octet-stream"
}
}
return fileManagerClientService.download({ fileNames: fileName })
.$promise
.then(function (data) {
console.log(data);
appInfo.setInfo({ message: "files downloaded successfully" });
try {
var blob = new Blob([data]);
if (typeof (fileName) == "string")
FileSaver.saveAs(blob, fileName);
else
FileSaver.saveAs(blob, "AllFiles.zip");
} catch (ex) {
console.log(ex);
}
},
请告诉我在 Angular 方面我缺少什么?我已经尝试了很多代码片段,但它们都不起作用!
最佳答案
伙计们,这个问题通过用 $http 调用替换 $resource 来解决。 这是工作代码,
function download(fileName) {
appInfo.setInfo({ busy: true, message: "loading files" });
return $http({
method: "GET",
url: "api/files/Download/",
params: { fileNames: fileName },
responseType: "arraybuffer"
}).then(function (data) {
appInfo.setInfo({ message: "files downloaded successfully" });
try {
var blob = new Blob([data.data]);
if (typeof (fileName) == "string")
FileSaver.saveAs(blob, fileName);
else
FileSaver.saveAs(blob, "AllFiles.zip");
} catch (ex) {
console.log(ex);
}
}, function (error) {
});
}
这是工作代码,我希望有人使用 $resource 有更好的解决方案,以及为什么它不能与 $resource 一起工作。
关于javascript - Angularjs 中的下载文件无法正确保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45681050/