我有一个WebApi/MVC应用程序,我正在开发一个angular2客户端(以取代MVC).我在理解Angular如何保存文件时遇到了一些麻烦.
该请求是确定的(正常工作与MVC,我们可以登录接收到的数据),但我无法弄清楚如何保存下载的数据(我主要是遵循同样的逻辑这篇文章).我确信这是非常简单的,但到目前为止,我根本不理解它.
组件功能的代码如下.我尝试过不同的方案,则斑的方法应该是,据我了解的路要走,但没有作用createObjectURL在URL.我甚至找不到URL窗口中的定义,但显然它存在.如果我使用该FileSaver.js模块,我会得到同样的错误.所以我猜这是最近发生的变化或者尚未实施.如何在A2中触发文件保存?
downloadfile(type: string){
let thefile = {};
this.pservice.downloadfile(this.rundata.name, type)
.subscribe(data => thefile = new Blob([data], { type: "application/octet-stream" }), //console.log(data),
error => console.log("Error downloading the file."),
() => console.log('Completed file download.'));
let url = window.URL.createObjectURL(thefile);
window.open(url);
}
Run Code Online (Sandbox Code Playgroud)
为了完整起见,获取数据的服务如下,但它唯一做的是发出请求并传递数据而不进行映射(如果成功):
downloadfile(runname: string, type: string){
return this.authHttp.get( this.files_api + this.title +"/"+ runname + "/?file="+ type)
.catch(this.logAndPassOn);
}
Run Code Online (Sandbox Code Playgroud) 我一直在尝试显示pdf文件,我从$http.post响应中获取blob .例如,pdf必须在应用程序中显示<embed src>.
我遇到了几个堆栈帖子,但不知怎的,我的例子似乎不起作用.
JS:
根据这份文件,我继续尝试......
$http.post('/postUrlHere',{myParams}).success(function (response) {
var file = new Blob([response], {type: 'application/pdf'});
var fileURL = URL.createObjectURL(file);
$scope.content = fileURL;
});
Run Code Online (Sandbox Code Playgroud)
根据我的理解,fileURL创建一个临时URL,博客可以将其用作参考.
HTML:
<embed src="{{content}}" width="200" height="200"></embed>
Run Code Online (Sandbox Code Playgroud)
我不知道如何在Angular中处理这个问题,理想的情况是(1)将它分配给范围,(2) '准备/重建'blob到pdf (3)将其传递给HTML使用<embed>因为我想要在应用程序中显示它.
我已经研究了一天以上但不知何故我似乎无法理解它在Angular中是如何工作的......让我们假设那里的pdf查看器库没有选项.
我正在meanjs使用https://github.com/DaftMonk/generator-angular-fullstack生成应用程序.我正在尝试生成.pdf文件phantomjs并将其下载到浏览器.
问题是下载的.pdf文件始终显示空白页,而不管页数.服务器上的原始文件未损坏.当我进一步调查时,发现下载的文件总是远大于磁盘上的原始文件.此问题也只发生在.pdf文件中.其他文件类型工作正常.
我试过几种方法,如res.redirect('http://localhost:9000/assets/exports/receipt.pdf');,res.download('client\\assets\\exports\\receipt.pdf'),
var fileSystem = require('fs');
var stat = fileSystem.statSync('client\\assets\\exports\\receipt.pdf');
res.writeHead(200, {
'Content-Type': 'application/pdf',
'Content-Length': stat.size
});
var readStream = fileSystem.createReadStream('client\\assets\\exports\\receipt.pdf');
return readStream.pipe(res);
Run Code Online (Sandbox Code Playgroud)
甚至我尝试过使用https://github.com/expressjs/serve-static 而不改变结果.
我是新来的nodejs.将.pdf文件下载到浏览器的最佳方法是什么?
更新: 我在Windows 8.1 64位计算机上运行它
我正在我的WebAPI中生成一个Excel文件.我将它"存储"在一个内存流中,然后将响应输入如下:
var result = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StreamContent(ms) };
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = projectName + ".xlsx"
};
// ms.Close();
return result;
Run Code Online (Sandbox Code Playgroud)
看起来服务器端工作正常.如果我将该内存流写入文件流,则会创建该文件,并且可以毫无问题地打开该文件.
在角度方面,如何在单击按钮时重新创建文件?
我试过这样的事情:
$scope.exportQuotas = function (projectName) {
homeService.GetQuotas(projectName, $routeParams.token, $scope.selection).then(
function (data) {
var dataUrl = 'data:application/octet-stream;' + data
var link = document.createElement('a');
angular.element(link)
.attr('href', dataUrl)
.attr('download', "bl.xlsx")
.attr('target', '_blank')
link.click();
})
}
Run Code Online (Sandbox Code Playgroud)
该文件已创建但当我尝试打开它时,它已损坏...我已尝试将数据类型更改为vnd.ms-excel in angular但它不起作用...我怎样才能获得该文件点击下载?
编辑 Jorg回答后,我尝试了以下内容:api返回的是:
Status Code: 200
Pragma: no-cache
Date: Tue, 02 Sep 2014 …Run Code Online (Sandbox Code Playgroud) 尝试了很多不同的方法后,没有任何方法可以帮助我.
最相似的问题是这一个如何在angularjs中阅读pdf流
我有一个AngularJS应用程序,它向我的PHP文件发送请求以生成PDF文件.我的控制器具有以下功能,我通过ng-click从按钮调用:
$scope.print = function() {
$http({
method : "post",
url : '/pdf/print_processor.php',
data : printdata,
//responseType : 'arraybuffer',
headers : {
'Content-type' : 'application/json'
}
}).success(function(response, status, headers) {
var file = new Blob([response], {type: 'application/pdf'});
var fileURL = URL.createObjectURL(file);
window.open(fileURL);
});
}
Run Code Online (Sandbox Code Playgroud)
主要原因是我必须将更多数据发送到PHP文件.printdata变量包含一个超过12 KB的嵌套JSON对象.所以我无法使用普通的GET或通过普通链接传递此数据作为URL的一部分.
请求正在运行,因为我可以直接调用print_processor.php(这给了我PDF),并且我使用相同的方法来创建发送电子邮件.就像上面提到的问题一样,我的回复也包含了pdf本身:
%PDF-1.5
3 0 obj
<</Type /Page
/Parent 1 0 R
/Resources 2 0 R
/Group <</Type /Group /S /Transparency /CS /DeviceRGB>>
/Contents 4 0 R>>
endobj
4 0 obj
<</Filter /FlateDecode …Run Code Online (Sandbox Code Playgroud) 我虽然这个问题可以解决我的问题,但我遵循了简单的HTTP服务器示例,但我遇到了一些我无法找到解决方案的问题.
我想在我的服务器中生成一个Excel文件,并通过Http响应将其返回给用户.我正在使用xlsxwriter在我的服务器中构建文件和金字塔框架.我已经设法构建文件并将其返回,但是第一个问题是LibreCalc(我在Ubuntu 14上测试)问我如何导入文件.我选择什么并不重要我收到此错误消息
一般错误.一般输入/输出错误.
如果我只是构建并保存文件而不将其作为响应返回,则打开正常.
我的代码来构建文件:
output = StringIO()
workbook = xlsxwriter.Workbook(output)
worksheet = workbook.add_worksheet()
# add the data
workbook.close()
excelcontent = output.getvalue()
response = Response(content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
body=excelcontent)
response.headers.add('Content-Disposition',
"attachment; filename=%s.xlsx" % nice_filename)
response.headers.add('Access-Control-Expose-Headers','Content-Disposition')
response.headers.add("Content-Length", str(len(excelcontent)))
response.headers.add('Last-Modified', last_modified)
response.headers.add("Cache-Control", "no-store")
response.headers.add("Pragma", "no-cache")
return response
Run Code Online (Sandbox Code Playgroud)
我处理回应:
$http({
method: 'POST',
url: url,
data: data},
{responseType: 'arraybuffer'}
).success(function (response, status, headers, config) {
var file = new Blob([response], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'});
var fileURL = URL.createObjectURL(file);
var result = document.getElementsByClassName("excel_hidden_download");
var anchor …Run Code Online (Sandbox Code Playgroud) 我已经生成/导出的xlsx使用文件json2xlsxNPM模块,并下载我使用的文件res.download(file)的功能express.js。
参考:使用 Express 从 NodeJS 服务器下载文件
以下是我的代码:
var fs = require("fs");
var json2xls = require('json2xls');
app.use(json2xls.middleware);
app.get('/export/:id', function (req, res) {
var id = req.params.id;
db.collection('provider').findOne({_id: mongojs.ObjectId(id)}, function (err, doc) {
var jsonArr = {};
var arr = jsonArr = doc;
var xls = json2xls(arr);
fs.writeFileSync('data.xlsx', xls, 'binary'); //file exported
//Now I want to download that file
res.setHeader('Content-disposition', 'attachment; filename=data.xlsx');
res.setHeader('Content-type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
res.download(__dirname + '/public/data.xlsx', function (error) {
console.log(error);
});
//res.json(doc); …Run Code Online (Sandbox Code Playgroud) 我的WebAPI方法,它返回HttpResponseMessage与.csv文件内容:
private static HttpResponseMessage FileAsAttachment(string file)
{
var now = DateTime.Now;
var result = new HttpResponseMessage(HttpStatusCode.OK);
result.Content = new StringContent(file);
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment"); //attachment will force download
result.Content.Headers.ContentDisposition.FileName = string.Format("Report-{0}.csv", now.ToString("MMMM"));
return result;
}
Run Code Online (Sandbox Code Playgroud)
所以我只需点击功能,即可调用服务器:
$scope.GenerateReport = function() {
var endDate = '2016-04-30';
UserDaysSummary.generateReport({endDate: endDate }, function (result) {
console.log("Export");
});
}
Run Code Online (Sandbox Code Playgroud)
但是我所得到的只是内部数据的回应.我试图使用这个和这个答案把它作为文件,但这并没有改变任何东西.
优选地,对服务器的调用具有GET方法,顺便说一句
我有一个REST API,如果我直接在浏览器中查询,它将返回一个JSON或CSV文件进行下载。我想对Angular HttpModule做同样的事情。
我的get请求很简单(它有一个查询字符串参数来指示要返回的文件格式):
public Submit(request: Request) {
...
return this.http.get(url).subscribe(response => {
//What here
});
}
Run Code Online (Sandbox Code Playgroud)
响应内容类型为application/octet-stream。我尝试将响应作为Blob进行处理,但这不起作用。我如何才能将服务器的响应传递到浏览器,然后让其下载文件?此方法是响应按钮单击的组件正在调用的服务的一部分
onClick() {
this._requestService.Submit(request); //This gets the Subscription response from the service, but I want it to let the broswer download the file
}
Run Code Online (Sandbox Code Playgroud) angularjs ×5
javascript ×3
angular ×2
download ×2
excel ×2
express ×2
mean-stack ×2
node.js ×2
pdf ×2
blob ×1
c# ×1
fileapi ×1
httpresponse ×1
json ×1
php ×1
pyramid ×1
python ×1
rest ×1
typescript ×1
xlsxwriter ×1