0
我的Web API方法要麼返回具有多個文件的單個文件或zip文件。這是Web API的實現。Angularjs中的下載文件無法正確保存
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);
}
}
這種方法完全正常工作,很好,我敢肯定,因爲當我要求通過「高級REST客戶端」,谷歌的Chrome擴展這種方法,文件被下載和完美的作品。
但是,當我通過Angularjs服務調用請求此方法時,文件無法打開。圖像文件給我下面的錯誤
以下爲PDF
,預計下對於ZIP
從Advance Rest Client行爲,但不能與Angularjs 。 以下是我的角碼
"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);
}
},
請告訴我什麼,我缺少的角邊?我已經嘗試了很多代碼片段,但它們不起作用!