【发布时间】:2018-01-22 16:16:03
【问题描述】:
我的 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 方面缺少什么?我尝试了很多代码 sn-ps,但它们都不起作用!
【问题讨论】:
标签: javascript angularjs web-services http asp.net-web-api