2017-01-11 4 views
0

xlsxテンプレートファイルとレスポンスにいくつかの値を持つファイルxlsxを使用するサービスを作成しようとしています。私はこれまでされており、リクエストでファイルを送信してリダイレクトせずに応答内のファイルをダウンロードする方法

index.htmlを

<input name="file" type="file" onchange="callthis()"/> 

script.js

// callthis sends the file from client to server 
function callthis() { 
var formData = new FormData($(this).files[0]); 

    $.ajax({ 
     url: '/uploadTemplate', 
     type: 'POST', 
     data: formData, 
     success: function (data) { 
      console.log(data); 
      alert(data) 
     }, 
     cache: false, 
     contentType: false, 
     processData: false 
    }); 
} 

serverRouter.jsコードの上に使用

router.post('/uploadTemplate', function(req, res, next){ 
    let uploadedFilePath = null; 

    // I'm using multer for handling formdata in the server 
    var upload = multer({ dest: Locator.temp.temp }); 

    //configure the multer 
    var storage = multer.diskStorage({ 
     destination: function (req, file, callback) { 
      callback(null, Locator.temp.temp); 
     }, 
     filename: function (req, file, callback) { 
      uploadedFilePath = file.fieldname + '-' + Date.now() + '.xlsx'; 
      callback(null, uploadedFilePath); 
     } 
    }); 

    var upload = multer({ storage : storage}).single('file'); 

    //in here i am uploading the file. 

    //and reading the file ugin XLSX modules. 

    //doing some changes to xlsx json object 

    //and write the data to a file in a temp folder 

    //i'm using res.download method to send downloadable file back to client 
    res.download(Path.join(Locator.temp.temp, uploadedFilePath)); 
    }); 
}) 

をやっていること、私がアップロードできますファイルと応答を取得します。成功メソッドは、いくつかの読めない文字を追加した詳細を出力します。しかし、私はファイルをダウンロードできませんでした。

ファイルをダウンロードするにはどうすればよいですか。このような状況のためには、異なる、より良いアプローチがありますか?

+0

可能性のある重複したあなたは、AJAX応答にダウンロードURLを送信してから、クライアント側のスクリプトはサーバーではURL

を開く持っている必要があります[res.download()は私の場合は動作しません](http://stackoverflow.com/questions/20176982/res-download-not-working-in-mycase) – zola

+0

nope。私たちがURLに移動するときに動作しています。しかし、この場合、私はURLにナビゲートしたくない – CoderS

答えて

0

AJAXリクエストにダウンロードを添付することはできません。

let response = {downloadUrl: Path.join(Locator.temp.temp, uploadedFilePath)} 
res.json(response) 

クライアントで:の

window.open(ajaxResponse.downloadUrl); 
関連する問題