2016-08-05 91 views
1

我寫的代碼,上傳所取出使用一個文件被上傳到谷歌雲存儲節點取到谷歌雲存儲桶。如何設置內容類型的文件中使用的node.js

到目前爲止一切正常,但我無法找到如何在GCloud上設置文件的Content-Type,否則文件將以application/octet-stream的格式下載。

這是我到目前爲止的代碼:

function saveImage(response, destFile) { 
    return new Promise((resolve, reject) => { 
    if (response.status !== 200) { 
     reject(new Error('Bad Response')); 
    } 

    // How do I set this on the file uploaded to the bucket? 
    const contentType = response.headers.get('Content-Type'); 

    try { 
     const file = bucket.file(destFile); 
     const writeStream = file.createWriteStream(); 

     writeStream.on('error', err => { 
     reject(err); 
     }); 

     writeStream.on('finish',() => { 
     resolve(getPublicUrl(destFile)); 
     }); 

     response.body.pipe(writeStream); 
    } catch (e) { 
     reject(e); 
    } 
    }); 
} 

回答

7

原來有對文件setMetadata方法,它可以調用傳遞內容類型作爲參數。以下是工作代碼的外觀:

function saveImage(response, destFile) { 
    return new Promise((resolve, reject) => { 
    if (response.status !== 200) { 
     reject(new Error('Bad Response')); 
    } 

    const contentType = response.headers.get('Content-Type'); 
    try { 
     const file = bucket.file(destFile); 

     const writeStream = file.createWriteStream({ 
     metadata:{ 
      contentType: contentType 
     } 
     }); 

     writeStream.on('error', err => { 
     reject(err); 
     }); 

     writeStream.on('finish',() => { 
     resolve(getPublicUrl(destFile)); 
     }); 

     response.body.pipe(writeStream); 
    } catch (e) { 
     reject(e); 
    } 
    }); 
} 
相關問題