[英]Nodejs serve base64 as Image
我正在嘗試將 base64 字符串作為帶有image/png
標頭的圖像提供。 標題設置正確,但沒有顯示圖像,我只能看到一個空白屏幕。 這是代碼:
request('someCustomLink', function (error, response, body) {
// someCustomLink gives the base64 string
var img = new Buffer(body, 'base64');
res.writeHead(200, {
'Content-Type': 'image/png',
'Content-Length': img.length
});
res.end(img);
});
這是我為達到此解決方案而遵循的鏈接。
任何幫助將不勝感激。
編輯這是我的 someCustomLink 的響應標頭(它可能有助於理解問題 betr)
Accept-Ranges:bytes
Content-Length:128778
Content-Type:image-jpeg
Date:Thu, 21 Dec 2017 06:03:52 GMT
ETag:"edc04d469779108860478b361b7427d7"
Last-Modified:Mon, 11 Dec 2017 08:54:32 GMT
Server:AmazonS3
x-amz-id-2:QlR39g0vC5CeOo6fdKzX9uFB+uiOtj61c0LKW2rQLcCPWllcKyfbpg93Yido+vZfzMzB3lmhbNQ=
x-amz-request-id:3EC77634D9A05371
這是獲取請求
var request = require('request').defaults({ encoding: null });
app.get('/thumb/:thumbLink', function(req, res) {
request('https://s3.amazonaws.com/my-trybucket/projectImages/'+req.params.thumbLink, function (error, response, body) {
//console.log('error:', error); // Print the error if one occurred
//console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
//console.log('body:', body); // Print the HTML for the Google homepage.
var img = new Buffer(body, 'base64');
res.writeHead(200, {
'Content-Type': 'image/png'
});
res.end(img);
});
});
-謝謝
您收到的響應包含data:image/png;base64,
。 在創建Buffer
之前,您已將其刪除。 請參閱下面的示例
request('https://s3.amazonaws.com/my-trybucket/projectImages/e31492f7314837a22a64395eee7cedfd', function(error, response, body) {
var img = new Buffer(body.split(',')[1], 'base64');
res.writeHead(200, {
'Content-Type': 'image/png',
'Content-Length': img.length
});
res.end(img);
})
在這個特定問題上也停留了很長時間,只是發現發送從 s3 返回的實際數據 Body 實際上足以顯示圖像。 這是我的實現(在打字稿中):
// a method in my Bucket class
async getObject(key: string) {
const params = {
Bucket: this.bucket, //my bucket name set in my constructor
Key: key,
};
return new Promise((resolve, reject) => {
s3.getObject(params, (err, data) => {
if (err) reject(err);
if(data) resolve(data.Body);
});
});
}
// the get request route
app.get(
"url/:folder/:id",
async (req: Request, res: Response) => {
const { folder, id } = req.params;
const image = (await new Bucket().getObject(`${folder}/${id}`)) as Buffer;
res.send(image);
}
);
我在我的服務器上收到錯誤ECONNRESET
。 原來res.end()
對此負責。 我用res.send()
替換了它,傳輸沒有問題。 這是我提供 base64 文件的通用解決方案
async (req: Request, res: Response) => {
const { id } = req.params;
//Get the image or file with your own method
const base64File = await GetBase64File(id)
const [fileInfo, fileData] = base64File.split(",");
const contentType = fileInfo.split(";")[0].replace("data:", "");
res.setHeader("Content-Type", contentType);
res.setHeader("Content-Length", fileData.length);
const buffer = Buffer.from(fileData, "base64");
res.send(buffer);
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.