【问题标题】:CSV file getting downloaded but not saved to computerCSV 文件已下载但未保存到计算机
【发布时间】:2021-09-10 19:46:55
【问题描述】:

我正在开发一个 Django 项目,在该项目中我使用我拥有的一些数据创建了一个 csv 文件,然后我希望用户能够下载它。该文件正在views.py中创建,如下所示:

def generate_csv_response(modelset, field_names, filename='export.csv'):
    """ Generate a CSV for all field_names in a DB model

        :param field_names is a dictionary which contains the model field name
            as a key and the CSV header display name as it's value
    """
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = f'attachment; filename="{filename}"'

    # create the CSV writer and write a header row to the file
    writer = csv.writer(response)
    writer.writerow([v for _, v in field_names.items()]) # display names are the values

    # write a row of all specified fields for each model in the modelset
    for m in modelset:
        row = [getattr(m, field) for field in field_names]
        writer.writerow(row)

    # return the generated HTTP response
    return response

class ConfigRuleViewSet(viewsets.ReadOnlyModelViewSet):
    queryset = ConfigRule.objects.all()
    serializer_class = ConfigRuleSerializer
    permission_classes = [permissions.IsAdminUser | ReadOnlyUser]
    config_rule_connector = AWSConfigRuleConnector()

    @action(detail=False, methods=['post'], permission_classes=[permissions.AllowAny])
    def refresh(self, request):
        account_id = json.loads(request.body)['account_id']
        if not account_id:
            logger.warn('Got blank account_id from ajax request: %s', account_id)

        if self.config_rule_connector.update(account_id):
            return Response(data={'updated': True, 'count': ConfigRule.objects.count()})
        return Response(data={'updated': False, 'error': 'Config Rule could not be updated', 'count': 0}, status=500)

    @action(detail=False, methods=['post', 'get'], permission_classes=[permissions.AllowAny])
    def csv(self, request):
        """ Get the ConfigRule information as a CSV """
        return generate_csv_response(
            ConfigRule.objects.all(),
            field_names={
                'name': 'Name',
                'aws_account_id': 'AWS Account ID',
                'arn': 'ARN',
                'owner': 'Owner',
                'description': 'Description',
                'state': 'State',
            },
            filename='config_rule_report.csv',
        )

这就是我正在做的使用 ajax 下载它:

{% block csv-button %}
    <button id="csv-btn" class="button is-link">CSV</button>
{% endblock %}
        var csvBtn = $("#csv-btn");

        // allow the table to be resync'd at any time by clicking the button
        csvBtn.click(function() {
            csvBtn.addClass("is-loading");
            $.ajax({
                url: "{{ api_csv_url }}",
                method: "GET",
                contentType: "text/csv",
                success: function(data) {
                    console.log("File has been successfully downloaded.");
                },
                complete: function() {
                    // complete runs on failure or success, so the button
                    // will always be re-enabled if a failure occurs
                    csvBtn.removeClass("is-loading");
                }
            });
        });

该文件确实已下载,因为我可以进入开发工具,然后联网,我在那里看到它。 csv/ 是正在下载的文件,我很难将其下载到用户的计算机中。任何帮助表示赞赏。谢谢!

【问题讨论】:

    标签: javascript jquery django ajax


    【解决方案1】:

    Ajax无法做到这一点,因为JS不会写入磁盘,所以你有2个解决方案

    1. 使用FileSystem API,这是非常新的,并非所有浏览器都支持。
    2. 使用经典锚标签下载文件,当您返回响应时,浏览器将拦截并处理下载。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-04-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-09
      • 1970-01-01
      相关资源
      最近更新 更多