2

我試圖從我的移動混合應用程序(Ionic 3)將圖片發送到我的Heroku後端(Node.js),並讓後端將圖片上傳到Firebase存儲,將新上傳的fil下載網址返回到移動應用程序。將base64編碼的jpeg上傳到Firebase存儲(Admin SDK)

請記住,我正在爲Node.js使用Firebase Admin SDK。

所以我送編碼圖像的Heroku以base64(我有一個在線的base64解碼器檢查編碼字符串,它是正常的),這是由下面的函數處理:

const uploadPicture = function(base64, postId, uid) { 
    return new Promise((resolve, reject) => { 
    if (!base64 || !postId) { 
     reject("news.provider#uploadPicture - Could not upload picture because at least one param is missing."); 
    } 

    let bufferStream = new stream.PassThrough(); 
    bufferStream.end(new Buffer.from(base64, 'base64')); 

    // Retrieve default storage bucket 
    let bucket = firebase.storage().bucket(); 

    // Create a reference to the new image file 
    let file = bucket.file(`/news/${uid}_${postId}.jpg`); 

    bufferStream.pipe(file.createWriteStream({ 
     metadata: { 
     contentType: 'image/jpeg' 
     } 
    })) 
    .on('error', error => { 
     reject(`news.provider#uploadPicture - Error while uploading picture ${JSON.stringify(error)}`); 
    }) 
    .on('finish', (file) => { 
     // The file upload is complete. 
     console.log("news.provider#uploadPicture - Image successfully uploaded: ", JSON.stringify(file)); 
    }); 
    }) 
}; 

我有2個主要問題:

  1. 上傳成功,但我當我去火力地堡存儲控制檯,還有當我嘗試顯示圖片的預覽,當我下載它,我無法從我的電腦打開它是一個錯誤。我想這是一個編碼的東西....?
  2. 如何檢索新上傳的文件下載網址?我期待在.on('finish)中返回一個對象,如upload()函數,但沒有返回(文件未定義)。我怎麼能檢索這個網址發回服務器響應?

我想避免使用upload()函數,因爲我不想在後端託管文件,因爲它不是專用服務器。

+0

我是這麼久,是因爲「上載」方法不起作用尋找答案。我的朋友,你很棒!奇蹟般有效!非常感謝你分享代碼和你的結果! –

回答

0

我的問題是,我在base64對象字符串的開頭添加了data:image/jpeg;base64,;我只是要刪除它。

對於下載網址,我做了以下內容:

const config = { 
     action: 'read', 
     expires: '03-01-2500' 
     }; 
     let downloadUrl = file.getSignedUrl(config, (error, url) => { 
     if (error) { 
      reject(error); 
     } 
     console.log('download url ', url); 
     resolve(url); 
     }); 
相關問題