内容处置:附件未触发下载对话框 [英] Content-Disposition:attachment not triggering download dialog

查看:89
本文介绍了内容处置:附件未触发下载对话框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试在NodeJS服务器上创建文件下载功能时遇到了一些意外行为. 我有一个REST(快速)API,它需要一些导出数据功能,该功能在服务器上创建CSV文件并使用res.download('path/to/file')触发下载. 响应标头包括

I've encountered some unexpected behavior when trying to create a file download functionality on my NodeJS server. I have a REST (express) API that calls for some export data function, which creates a CSV file on the server and uses res.download('path/to/file') to trigger the download. Response headers include

Content-Disposition:attachment; filename="indicators.csv"
Content-Length:30125
Content-Type:text/csv; charset=UTF-8

所以一切似乎都井然有序.

so everything seems to be in order.

问题是,我从服务器得到的响应为纯文本格式.响应具有CSV文件包含的所有数据,但没有像我预期的那样触发浏览器的文件下载对话框. 我在Chrome和FF上都尝试过.问题仍然存在.

The thing is, I get the response from the server as plain text. The response has all the data the CSV file contains, but does not trigger the browser's file download dialog like I intended. I tried both on Chrome and FF. The problem persists in both.

有什么想法吗?

更新

我设法通过创建一个虚拟表单并使用其提交操作进行AJAX调用来使其工作.但这是一个丑陋的骇客,我仍在寻找更优雅的解决方案.

I managed to make it work by creating a dummy form, and using its submit action to make my AJAX call. But it's an ugly hack, and I'm still looking for a more elegant solution.

推荐答案

标题不是问题.问题是您正在通过ajax调用查询下载URL,该调用不会调用浏览器下载对话框.您的选择归结为以下几点:

Headers are not the issue. The issue is that you are querying the download url via an ajax call, which will not invoke the browser download dialog. Your options boil down to the following:

  1. 使用提交到您的下载URL的表单.用户不必与可见的表单进行交互,而可以使用JavaScript创建表单并通过调用form.submit-

  1. Use a form that is submitted to your download url. Instead of having a visible form a user has to interact with, create a form with JavaScript and submit it programmatically by calling form.submit - Handle file download from ajax post

window.location指向下载URL.您可以在当前窗口中执行此操作-使用ajax请求下载文件,或添加一个新的- res.download( )在我的情况下不起作用

Point window.location to the download url. You can do this in the current window - download file using an ajax request , or in a new one - res.download() not working in my case

这篇关于内容处置:附件未触发下载对话框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆