如何将图片转换为Base64字符串?已尝试代码但无法运行
Fixing Image-to-Base64 Conversion with Request Library
Hey there! Let's troubleshoot why your code isn't generating valid Base64 from your image request.
The Root Problem
The request library automatically parses response bodies as UTF-8 strings by default. Since images are binary data, this encoding messes up the raw bytes—so when you try to convert that mangled string to Base64, you end up with invalid or broken output.
The Fixed Code
All you need to do is add encoding: null to your options object. This tells request to return the raw binary buffer instead of a string, which we can convert directly to Base64 without data loss. Here's the updated version:
var request = require('request'); let options = { url: imgUrl, headers: { "Authorization": imgauth }, encoding: null // Critical fix: preserves raw binary data }; request(options, function(error, response, body) { // Add error handling to catch issues like bad URLs or auth failures if (error) { console.error('Request failed:', error); return; } // Body is now a Buffer, so we can convert it straight to Base64 var base64data = body.toString('base64'); console.log(base64data); });
Quick Notes
- The
contentType: "base64"you had in your original options isn't a valid setting for therequestlibrary—you can safely remove it. - Always include error handling to catch network issues, invalid credentials, or broken image URLs.
- If you're working in a newer Node.js environment, you might want to consider modern alternatives like
node-fetchoraxios, but the fix above works perfectly with therequestlibrary.
内容的提问来源于stack exchange,提问作者tamilmani
相关产品推荐
相关产品推荐

