[英]Download file with filesaver.js with angularJS from web api response c#
Im using the filesaver js library for download files... i'm generating a endpoint with web api that returns my file from base64 but i don't know how to return base64 as Blob for download with filesaver.... 我正在使用filesaver js库下载文件...我正在使用Web API生成一个终结点,该终结点从base64返回我的文件,但我不知道如何将base64作为Blob返回以通过filesaver下载....
public HttpResponseMessage GetFile(int id)
{
string mybase64file = GetBase64File(id)
byte[] bytes = Convert.FromBase64String(mybase64file );
MemoryStream ms = new MemoryStream(bytes);
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
result.Content = new StreamContent(ms);
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
result.Content.Headers.ContentDisposition.FileName = "someFileName.pdf";
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
return result;
}
AngularJS service: AngularJS服务:
function download() {
var deferred = $q.defer()
$http.get('url', {
headers: {
'Content-type': 'application/octet-stream',
},
responseType: 'blob'
})
.success(function (response) {
saveAs(response, 'someName.pdf')
})
.error(function (err) {
deferred.reject(err)
})
return deferred.promise
}
When the angularjs service recieve to response, im call the "saveAs" function, but this generate the next error: 当angularjs服务收到响应后,我会调用“ saveAs”函数,但这会产生下一个错误:
"angular.min.js:118 TypeError: Failed to execute 'createObjectURL' on 'URL': No function was found that matched the signature provided."
“ angular.min.js:118 TypeError:无法在'URL'上执行'createObjectURL':找不到与提供的签名匹配的函数。”
To return a file from ASP MVC CORE, use: 要从ASP MVC CORE返回文件,请使用:
return File(stream, "application/octet-stream");
return FileStreamResult(stream, "application/octet-stream");
return PhysicalFileResult("path to file", "application/octet-stream");
With that, you dont even need filesaver js library, the file will download automatically once that link is requested. 这样,您甚至不需要filesaver js库,一旦请求该链接,文件将自动下载。
One more thing: You cant download a file with Ajax ( ....$http.get('url', {....
)! 还有一件事:您无法使用Ajax下载文件(
....$http.get('url', {....
)!
You could use Fetch API do get the blob, see implementation here: https://stackoverflow.com/a/9970672/3563013 您可以使用Fetch API来获取Blob,请参见此处的实现: https : //stackoverflow.com/a/9970672/3563013
To address the specific error ( "angular.min.js:118 TypeError: Failed to execute 'createObjectURL' on 'URL': No function was found that matched the signature provided."
), its possible window.URL.createObjectURL is not supported in the browser you are using to test. 为了解决特定的错误(
"angular.min.js:118 TypeError: Failed to execute 'createObjectURL' on 'URL': No function was found that matched the signature provided."
),不支持其可能的window.URL.createObjectURL在您用来测试的浏览器中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.