自动下载不适用于Django FileResponse



我需要让django自动下载生成的文件。

在线尝试了所有不同的解决方案,它们都无法使用。

views.py

def validate(request):
    if request.method == 'POST':
        filename = request.POST.get('source_file')
        file_path = os.path.join(settings.MEDIA_ROOT, 'SourceFiles', filename)
        region = request.POST.get('region')
        product_type = request.POST.get('product_type')
        result = validateSource.delay(file_path, region, product_type)
        output_filepath, log_filepath = result.get()
        if os.path.exists(output_filepath) and os.path.exists(log_filepath):
            zip_filename = zipFiles([output_filepath, log_filepath], filename)
            zip_filepath = os.path.join(settings.MEDIA_ROOT, zip_filename)
            response = FileResponse(open(zip_filepath, 'rb'), as_attachment=True)
            return response
        raise Http404

模板:表单帖子的代码。

     $(document).on('submit', '#productForm', function(e){
       e.preventDefault();
       var inputFilePath = document.getElementById('sourceFileInput').files.item(0).name;
        $.ajax({
            method: 'POST',
            url: 'validate/',
            data: {
              source_file: inputFilePath,
              region: $("#Region-choice").val(),
              product_type: $("#Product-type").val()}
            })
            .done(function(){
                document.getElementById('lblStatus').innerHTML = "Result: <br/>"
                document.getElementById('lblStatusContent').innerHTML = "Success!"
            })
            .fail(function(req, textStatus, errorThrown) {
                document.getElementById('lblStatus').innerHTML = "Result: <br/>"
                alert("Something went wrong!:" + textStatus + '  ' + errorThrown )
            });
    });
 });

无法通过AJAX(XHR(请求下载文件。因此,您需要将用户实际(设置window.location(重定向到下载文件的视图。或者,您可以添加当前页面成功发布按钮的结果,以便用户可以下载文件。无论如何,您需要将文件下载移至其他视图,以便标准获取请求可以获取。

但是您的代码返回Django中的文件(使用FileResponse(是正确的。

也有一种解释,另一种在这里这样做的方法

def validate(request):
    if request.method == 'POST':
        filename = request.POST.get('source_file')
        file_path = os.path.join(settings.MEDIA_ROOT, 'SourceFiles', filename)
        region = request.POST.get('region')
        product_type = request.POST.get('product_type')
        result = validateSource.delay(file_path, region, product_type)
        output_filepath, log_filepath = result.get()
        if os.path.exists(output_filepath) and os.path.exists(log_filepath):
            zip_filename = zipFiles([output_filepath, log_filepath], filename)
            zip_filepath = os.path.join(settings.MEDIA_ROOT, zip_filename)
            with open(zip_filepath, 'rb') as fh:
                response = HttpResponse(fh.read(), content_type="application/force-download")
                response['Content-Disposition'] = 'attachment; filename=' + os.path.basename(zip_filepath)
                return response
        raise Http404

最新更新