2017-07-12 33 views
0

我一直在爲這個問題苦苦掙扎,需要你們的幫助!我正試圖簡化從我的網站下載報告的過程。隨着節點,這是相當簡單的用readStream,像這樣:使用客戶端Javascript保存來自Node的readStream的圖像

router.post('/report', (req, res) => { 
    const filename = 'test.png'; 
    const filePath = path.join(__dirname, filename); 
    fs.exists(filePath, exists => { 
     if (exists) { 
      const stat = fs.statSync(filePath); 
      res.writeHead(200, { 
       'Content-Type': 'image/png', 
       'Content-Length': stat.size, 
       'Content-Disposition': 'attachment; filename=' + filename, 
      }); 
      fs.createReadStream(filePath).pipe(res); 
     } else { 
      res.writeHead(400, { 'Content-Type': 'text/plain' }); 
      res.end('ERROR File does NOT Exists'); 
     } 
    }); 
}); 

現在,如果我嘗試這與郵差或其他一些API測試儀,它完美的作品,該文件被下載並正確保存。現在我正努力讓這個工作在我的前端。我目前正在運行AngularJS,並嘗試使用FileSaver.js作爲接收這些數據並保存它的方法,但它永遠不會工作。該文件已保存,但數據不可讀,也就是圖像預覽器說圖像已損壞。我認爲我錯誤地創建了Blob?

function exportReport(_id) { 
    this.$http 
     .post(
      '/api/report', 
      { _id }, 
      { 
       headers: { 
        'Content-type': 'application/json', 
        Accept: 'image/png', 
       }, 
      } 
     ) 
     .then(data => { 
      console.log(data); 
      const blob = new Blob([data], { 
       type: 'image/png', 
      }); 
      this.FileSaver.saveAs(blob, 'testing.png'); 
     }); 
} 

控制檯日誌結果是這樣:

Object {data: "�PNG 
↵↵ 
IHDRRX��iCCPICC Profi…g�x @� @������Z��IEND�B`�", status: 200, config: Object, statusText: "OK", headers: function} 

我是想給object.data解碼?

回答

1

嘗試增加responseType: 'blob'請求並忽略創建一個新斑塊:

function exportReport(_id) { 
    this.$http 
     .post(
      '/api/report', 
      { _id }, 
      { 
       headers: { 
        'Content-type': 'application/json', 
        Accept: 'image/png', 
       }, 
       responseType: 'blob' 
      } 
     ) 
     .then(data => { 
      console.log(data); 
      this.FileSaver.saveAs(data.data, 'testing.png'); 
     }); 
} 
+0

我已經試過了,原來的文件大小爲75KB。但下載的破碎圖像是130kb?該圖像仍然被認爲是破碎的,無法打開。 – StefanM

+0

如果您向HTTP請求添加了responseType:blob選項,該怎麼辦?看到我編輯的答案。 – Svenskunganka

+0

完美!我缺少responseType,所以我不需要創建blob。它現在工作正常。 – StefanM