我的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扩展程序文件会被下载并完美运行。
但是当我通过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);
}
},
请告诉我在Angular方面我缺少什么?我尝试了很多代码片段,但它们没有用!
答案 0 :(得分:2)
所以小伙子们,通过用$ 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。