2017-01-24 10 views
1

ユーザーが15MBのファイルを自分のWebにアップロードできるようにしようとしているところから、そのファイルを私のWebサービスに投稿し、 (pdfファイル)をダウンロードして、ユーザーにダウンロードしてもらうことができます。ファイルをアップロードした後、生成された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のWebコード

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のWebサービスのコード

@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 Generatorでは、ReportLabのを使用しています io.BytesIO()上でPDFファイルを書き込み、とそれを返しますoutput = self.buff.getvalue()

1.-私はwindow locationのことで間違っていますか?

2.ファイルタイプに問題がありますか?

私はこの2日です。今は助けが必要です。

ありがとうございました。あなたはwindow.location = '/Download?file=' + returnValue;に求めているものだ

答えて

1

However, I'm ending in a URL like this with no prompt to download anything, just a 404 error: http://localhost:10080/Download?file=%PDF-1.4%%EF%BF%BD%EF%B (etc)

は、あなたが/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 
    } 
}) 
+0

マスター!私がそれを読んだとき、いくつかのことは私の心の中に一緒には収まりませんでしたし、少し懐疑的でした。しかし、試した後、魅力のように動作します!どうもありがとうございました。しかし、なぜ私はそれを動作させるために両方のライブラリを使用しなければならなかったのかを完全には理解していません。 – mclzc

+0

zipファイルをバックエンドに 'POST 'したら、2つのことをしたい:1 /バイナリレスポンスを取得し、2 /ダウンロードをトリガする。 1/jQueryプラグイン( '$ .ajax'はバイナリコンテンツ自体を壊します)または' responseType = "blob"(あなたは既にjQueryを使用していますので、最初のソリューションを使用しました)の未処理の 'XMLHttpRequest'が必要です。 2 /に対して、(まだ)各ブラウザに実装されているAPIはありません。 'FileSaver.js'は' saveAs'でそれを行うためのさまざまな方法を包みます。 –

関連する問題