【问题标题】:Allow user to download a generated pdf file after uploading a file允许用户在上传文件后下载生成的 pdf 文件
【发布时间】:2017-06-08 18:11:50
【问题描述】:

我正在尝试允许用户将 15 MB 的文件上传到我的网站,从那里将该文件发布到我的网络服务,接收响应(pdf 文件)并将其提供给用户他可以下载。

但是,我以这样的 URL 结尾,没有提示下载任何内容,只是 404 错误:http://localhost:10080/Download?file=%PDF-1.4%%EF%BF%BD%EF%B (etc)

几点:

  • 首先我将压缩文件
  • 由于上一点,我使用Ajax来发布文件

Ajax 代码

    $("#file").on("change", function(evt) {

        var files = evt.target.files;

        /*  Create zip file representation */
        var zip = new JSZip();
        /* Name, content */
        zip.file("data.zip", files[0]);

        zip.generateAsync({
            compression: 'DEFLATE',
            type: 'blob'
        }).then(function(zc) { // Function called when the generation is complete
            /* Create file object to upload */
            var fileObj = new File([zc], "compressed-data");

            /* form data oject */
            var formData = new FormData();
            /* $('#file')[0].files[0] */
            formData.append('attachments', fileObj);

            $.ajax({
                type: "POST",
                url: $("form#data").attr("action"),
                data: formData,
                contentType: false,
                processData: false,
                success: function (returnValue, textStatus, jqXHR ) {
                    window.location = '/Download?file=' + returnValue;
                }
            })

Python 网页代码

def post(self):
    attachments = self.request.POST.getall('attachments')
    #handle the attachment
    _attachments = [{'content': f.file.read(),
                     'filename': f.filename} for f in attachments]

    # Use the App Engine Requests adapter. This makes sure that Requests uses
    # URLFetch.
    requests_toolbelt.adapters.appengine.monkeypatch()

    #web service url
    url = 'http://localhost:8080'

    files = {'attachments': _attachments[0]["content"]}

    resp = requests.post(url, files=files)

    self.response.headers[b'Content-Type'] = b'application/pdf; charset=utf-8'
    self.response.headers[b'Content-Disposition'] = b'attachment; filename=report.pdf'
    self.response.out.write(resp.content)

Python 网络服务代码

@app.route('/', methods=['POST'])
def hello():

    #the attached ZIPPED raw data
    f = request.files["attachments"]
    #to unzip it
    input_zip = ZipFile(f)
    #unzip
    data = [input_zip.read(name) for name in input_zip.namelist()]

    generator = pdfGenerator(io.BytesIO(data[0]))
    return generator.analyzeDocument()

pdf 生成器使用 Reportlab,将 pdf 写入 io.BytesIO() 并返回 output = self.buff.getvalue()

1.- 我在 window location 上做错了什么?

2.- 我的文件类型有问题吗?

我已经完成了两天,现在我需要帮助。

谢谢。

【问题讨论】:

    标签: ajax web-services google-app-engine web webapp2


    【解决方案1】:

    但是,我以这样的 URL 结尾,没有提示下载任何内容,只是 404 错误:http://localhost:10080/Download?file=%PDF-1.4%%EF%BF%BD%EF%B(等)

    这就是您在window.location = '/Download?file=' + returnValue; 中提出的问题,您将用户重定向到/Download

    当您致电您的服务时,您应该要求Blob 回复。然后,使用saveAs (or FileSaver.js, a polyfill) 触发下载。

    据我所知,$.ajax 不允许您开箱即用地下载二进制内容(它会尝试从 UTF-8 解码您的二进制文件并破坏它)。要么使用 jQuery 插件(如 jquery.binarytransport.js),要么直接使用 xhr。

    $.ajax({
        type: "POST",
        url: $("form#data").attr("action"),
        data: formData,
        contentType: false,
        processData: false,
        dataType: 'binary',                       // using jquery.binarytransport.js
        success: function (returnValue, textStatus, jqXHR ) {
            // Default response type is blob
            saveAs(returnValue, "result.pdf");    // using FileSaver.js
        }
    })
    

    【讨论】:

      猜你喜欢
      • 2018-12-15
      • 1970-01-01
      • 2023-03-21
      • 2013-01-29
      • 1970-01-01
      • 1970-01-01
      • 2011-10-20
      • 1970-01-01
      • 2023-03-11
      相关资源
      最近更新 更多