2017-06-12 14 views
0

我正在創建一個API,以便爲Google的API創建授權的API調用,特別是針對此問題的Drive。我的API工作正常,並使用Google's Node API來提出請求。當我火了,以this資源的請求,我回來瞭如下回應:將原始圖像字節呈現給響應主體

{ 
"kind": "drive#file", 
"id": "...", 
"name": "bookmobile.jpg", 
"mimeType": "image/jpeg" 
} 

我用上面的反應,以確定MIME類型,我稍後顯示的文件。然後,我隨後調用相同的端點,但指定alt=media作爲下載Google's Guide中指定的文件的選項。如果我console.logres.send()的響應,我得到下面的輸出:

image bytes

,我們可以看到的是,從API調用原始圖像的字節數。如何正確地將這些字節呈現給響應主體?我的代碼如下:

// DriveController.show 
exports.show = async ({ query, params }, res) => { 
    if (query.alt && query.alt.toLowerCase().trim() === 'media') { 
    // Set to JSON as we need to get the content type of the resource 
    query.alt = 'json' 

    // Get the Files Resource object 
    const options = createOptions(query, params.fileId) 
    const filesResource = await Promise.fromCallback(cb => files.get(options, cb)) 

    // Grab the raw image bytes 
    query.alt = 'media' 
    await createAPIRequest(createOptions(query, params.fileId), 'get', res, filesResource) 
    } else { 
    await createAPIRequest(createOptions(query, params.fileId), 'get', res) 
    } 
} 

async function createAPIRequest (options, method, res, filesResource = {}) { 
    try { 
    const response = await Promise.fromCallback(cb => files[method](options, cb)) 
    if (filesResource.hasOwnProperty('mimeType')) { 
     // Render file resource to body here 
    } else { 
     res.json(response) 
    } 
    } catch (error) { 
    res.json(error) 
    } 
} 

經過這裏所有不同的答案搜索似乎指向以下:

res.type(filesResource.mimeType) 
const image = Buffer.from(response, 'binary') 
fs.createReadStream(image).pipe(res) 

但這殺死了我的快速應用,出現以下錯誤:

Error: Path must be a string without null bytes

我將如何正確渲染這些原始圖像字節到響應正文?

+0

相反fs.createReadStream'的',只是做'res.send(圖像)',甚至更好,'res.end(圖)' 。 –

+0

@JulianGoacher我使用'res.send'取回以下內容:http://i.imgur.com/e0lNDfG.png它看起來像是渲染,但我不確定。 –

+0

或者在發送之後調用res.end(),或者使用'res.end(image)'。 –

回答

0

Google API客戶端默認返回二進制數據作爲字符串,這會在圖像數據發生時破壞圖像數據。 (這個問題在這個線程上討論:https://github.com/google/google-api-nodejs-client/issues/618)。要解決,請求文件內容時使用encoding: null選項:

files[method](options, { encoding: null }, cb))