如何通过Node.js向Azure Blob Storage上传带正确Content-Type的图片
Hey there! I’ve run into this exact issue before—Azure Blob Storage falling back to application/octet-stream even when trying to set a custom Content-Type. Let’s get this sorted out for you.
The Root Cause
Your current httpHeaders object uses raw HTTP header names (like x-ms-blob-content-type), but the Azure Node.js SDK expects camelCase property names for the blobHTTPHeaders option. The SDK doesn’t recognize the raw header keys, so it ignores them and uses the default Content-Type.
Corrected Code Example
Here’s how to properly configure the headers and upload your image:
const { BlockBlobClient } = require("@azure/storage-blob"); const getStream = require("into-stream"); // Assuming you're using this package for stream conversion // Initialize your BlockBlobClient as before const bc = new BlockBlobClient( rhcConfig.STORAGE_CONNECTION_STRING, rhcConfig.CONTAINER_NAME, `IMAGES/${fileName}` ); const buff = Buffer.from(file, "base64"); const stream = getStream(buff); const streamLength = buff.length; // Correct header configuration using camelCase property names const uploadOptions = { blobHTTPHeaders: { blobCacheControl: "max-age=1000", // Fixed cache-control format (original "1000" isn't valid) blobContentType: "image/png", // This maps to x-ms-blob-content-type under the hood blobContentMD5: md5Hash, // Pass the MD5 hash directly (no template string needed) blobContentEncoding: "compress", blobContentLanguage: "en", blobContentDisposition: `attachment; filename="${fileName}"` // Adjusted to a valid disposition value } }; try { const result = await bc.uploadStream(stream, streamLength, 4 * 1024 * 1024, uploadOptions); console.log("Upload succeeded!", result); } catch (error) { console.error("Upload failed:", error); }
Key Notes
- CamelCase Property Names: The
blobHTTPHeadersobject expects properties likeblobContentType,blobCacheControl, etc.—not the rawx-ms-*header names. The SDK handles translating these to the correct HTTP headers automatically. - Dynamic Content-Type (Optional): If you’re uploading different image types (PNG, JPG, etc.), use a package like
mime-typesto auto-detect the correct MIME type:const mime = require("mime-types"); const contentType = mime.lookup(fileName) || "image/png"; // Fallback to PNG if detection fails - Block Size: I adjusted the block size parameter in
uploadStreamto 4MB (a common optimal value)—using1will make your uploads very slow for larger images. - Valid Cache-Control: Your original
"1000"value isn’t a valid cache-control directive. Usemax-age=1000to specify the cache duration in seconds.
Verify the Result
After uploading, check the blob’s properties in the Azure Portal—you should now see the correct image/png (or your desired MIME type) under the Content-Type field.
内容的提问来源于stack exchange,提问作者Debadatta Meher

