Fix 'Invalid file image: unsupported mimetype application/octet-stream' in OpenAI Node SDK
Error message
Invalid file 'image': unsupported mimetype ('application/octet-stream'). Supported file formats are 'image/png'.This error occurs when the OpenAI API receives a file that it cannot identify as a supported image format, specifically when the MIME type is detected as application/octet-stream instead of image/png or another allowed type. The most common cause is that the file being sent lacks a proper file extension or is being read in a way that strips the filename metadata, preventing the API from determining the correct MIME type.
What Causes This Error
The error message Invalid file 'image': unsupported mimetype ('application/octet-stream'). Supported file formats are 'image/png'. appears when the OpenAI API's file validation rejects an image input. The API expects files to have a recognized MIME type, and application/octet-stream is the generic fallback for binary data with no identifiable type. The following causes are documented across the sources.
1. Missing or incorrect file extension on the uploaded file
According to the GitHub issue discussion (source 2), the user reports that the same API call worked previously without this error. The issue arose when using fs.createReadStream(patchFn) where patchFn and maskFn are file paths. If the file path does not end with .png, .jpg, .jpeg, .webp, or .gif (non-animated), the API may default to application/octet-stream. The official documentation (source 1) lists supported file types as PNG (.png), JPEG (.jpeg and .jpg), WEBP (.webp), and non-animated GIF (.gif). Any other extension, or no extension, will cause the API to reject the file.
2. Using a file object without a filename attribute
When using the OpenAI Node SDK, the openai.images.edit method accepts a file path or a stream. If you pass a stream created with fs.createReadStream without ensuring the filename is preserved, the SDK may not send the filename to the API. The API then inspects the raw bytes to guess the MIME type, and if the file is a PNG but the bytes are ambiguous or the file is corrupted, it may fall back to application/octet-stream. The GitHub issue (source 2) shows the user calling openai.images.edit with image: fs.createReadStream(patchFn) and mask: fs.createReadStream(maskFn). If patchFn or maskFn are variables that contain paths without extensions, the stream will have no filename, leading to the error.
3. Sending a PIL image object directly (Python SDK)
Although the primary platform is the Node SDK, the error also appears in the Python SDK when using PIL images. Source 3 describes a scenario where a PIL Image.Image object is passed to the API without being saved to a file with a proper extension. The API cannot infer the MIME type from an in-memory image object, so it defaults to application/octet-stream. This is relevant for Node users who might be using libraries like sharp or jimp to manipulate images before sending them.
4. File corruption or incomplete download
If the image file is corrupted or was not fully downloaded, the API may fail to detect its format. The official documentation (source 1) requires images to be "clear enough for a human to understand" and free of watermarks or logos, but corruption can also cause MIME type detection to fail. This is less common but mentioned in community discussions as a potential cause when the error appears intermittently.
5. Using an unsupported image format
The API only supports PNG, JPEG, WEBP, and non-animated GIF. If you attempt to upload a TIFF, BMP, SVG, or animated GIF, the API will reject it with this error. The official documentation (source 1) explicitly lists the supported file types. Animated GIFs are not supported, and the API will treat them as unsupported.
How to Fix It
The following solutions are ordered by likelihood of success according to the sources. Each solution includes exact steps and code examples.
Solution 1: Ensure the file path has a .png extension (Most Common Fix)
This fix comes from the GitHub issue (source 2) and the official documentation (source 1). The API relies on the filename extension to determine the MIME type. If your file path does not end with .png, rename the file or adjust the path variable.
Steps:
-
Verify that the file you are trying to upload is actually a PNG image. You can check this by opening it in an image viewer or using a tool like
fileon macOS/Linux:file path_to_your_image.pngThe output should say something like
PNG image data, 1024 x 1024. -
If the file is not a PNG, convert it using an image editor or a command-line tool like ImageMagick:
convert input.jpg output.png -
Ensure the variable
patchFnandmaskFnin your code contain the full path including the.pngextension. For example:const patchFn = '/path/to/your/image.png'; const maskFn = '/path/to/your/mask.png'; -
Update your API call to use these paths:
const response = await openai.images.edit({ image: fs.createReadStream(patchFn), prompt, mask: fs.createReadStream(maskFn), n: 1, size: "1024x1024", response_format: "b64_json", }); -
Run your code. If the error persists, proceed to Solution 2.
Why this works: The OpenAI API uses the file extension to set the Content-Type header when uploading the file. Without a recognized extension, the API defaults to application/octet-stream. By providing a .png extension, the SDK sends the correct MIME type.
Solution 2: Use a file path instead of a stream with a missing filename
If you are using fs.createReadStream with a path that has no extension, or if the stream is created from a buffer without a filename, the API may not receive the filename. The GitHub issue (source 2) shows that the user's code uses fs.createReadStream(patchFn) where patchFn is a variable. If patchFn is a path without an extension, the stream will not carry filename information.
Steps:
-
Instead of passing a stream, pass the file path directly if your SDK version supports it. The OpenAI Node SDK version 4.95.0 (as reported in source 2) accepts both streams and file paths. Check the documentation for your SDK version.
-
If you must use a stream, ensure the stream has a
pathproperty that includes the filename. You can do this by creating a read stream from a file with a proper name:const imageStream = fs.createReadStream('/absolute/path/to/image.png'); console.log(imageStream.path); // Should output the full path -
Alternatively, use the
toFilemethod if available, or convert the stream to a buffer and use thecreateReadStreamwith a proper path. -
Test the API call again.
Why this works: The OpenAI Node SDK uses the path property of the stream to extract the filename. If the stream lacks this property, the API cannot determine the MIME type.
Solution 3: Write the image to a temporary file with a .png extension (Python SDK, but adaptable to Node)
Source 3 provides a solution for the Python SDK that involves writing the image to a named temporary file with the correct extension. This approach can be adapted to Node.js if you are working with in-memory image buffers.
Python example (from source 3):
import tempfile
from PIL import Image
def convert_for_openai(image: Image.Image, format: str) -> str:
with tempfile.NamedTemporaryFile(delete=False, suffix=f".{format}") as temp_file:
image.save(temp_file, format=format.upper())
return temp_file.name
client.images.edit(
model="gpt-image-1",
image=[
open(convert_for_openai(my_image, "png")),
],
prompt="my prompt",
size="1024x1024",
quality="high",
)
Node.js adaptation:
If you are using a library like sharp to manipulate images in Node.js, you can write the buffer to a temporary file:
const fs = require('fs');
const path = require('path');
const os = require('os');
const sharp = require('sharp');
async function convertForOpenAI(imageBuffer) {
const tempDir = os.tmpdir();
const tempFilePath = path.join(tempDir, `image_${Date.now()}.png`);
await sharp(imageBuffer).png().toFile(tempFilePath);
return tempFilePath;
}
// Usage
const imageBuffer = await sharp('input.jpg').resize(1024, 1024).toBuffer();
const tempFilePath = await convertForOpenAI(imageBuffer);
const response = await openai.images.edit({
image: fs.createReadStream(tempFilePath),
prompt: 'my prompt',
mask: fs.createReadStream('/path/to/mask.png'),
n: 1,
size: '1024x1024',
response_format: 'b64_json',
});
// Clean up the temp file
fs.unlinkSync(tempFilePath);
Why this works: Writing the image to a file with a .png extension ensures that the file system and the OpenAI SDK can correctly identify the MIME type. The temporary file approach is useful when you are generating images dynamically.
Solution 4: Verify the file is not corrupted and is a valid PNG
If the file has a .png extension but is corrupted, the API may still reject it. The official documentation (source 1) does not explicitly mention corruption, but community reports indicate that invalid files can cause this error.
Steps:
-
Open the file in an image viewer to confirm it displays correctly.
-
Use a command-line tool to check the file integrity:
pngcheck -v your_image.pngIf
pngcheckis not installed, you can install it via Homebrew on macOS:brew install pngcheck. On Linux, use your package manager. -
If the file is corrupted, regenerate it from the original source.
-
If you are downloading the file from a URL, ensure the download completes fully. You can check the file size:
ls -la your_image.pngCompare it to the expected size.
Why this works: A valid PNG file has a specific header (magic bytes 89 50 4E 47). If the header is missing or damaged, the API cannot identify the file as PNG and falls back to application/octet-stream.
Solution 5: Use the file ID approach (Responses API)
The official documentation (source 1) describes an alternative method for passing images: uploading the file to the Files API first and then using the file ID. This bypasses the MIME type detection issue because the file is already stored on OpenAI's servers with known metadata.
Steps:
-
Upload the image file using the Files API with the purpose set to
"vision":const fs = require('fs'); const OpenAI = require('openai'); const openai = new OpenAI(); async function createFile(filePath) { const fileContent = fs.createReadStream(filePath); const result = await openai.files.create({ file: fileContent, purpose: "vision", }); return result.id; } const fileId = await createFile('/path/to/your/image.png'); -
Use the file ID in your request (for Responses API, not Images Edit API):
const response = await openai.responses.create({ model: "gpt-5.6", input: [ { role: "user", content: [ { type: "input_text", text: "what's in this image?" }, { type: "input_image", file_id: fileId }, ], }, ], }); console.log(response.output_text);
Note: The file ID approach is documented for the Responses API, not the Images Edit API. If you are using openai.images.edit, this solution may not apply directly. However, it is a valid workaround for vision-related tasks.
Why this works: When you upload a file via the Files API, OpenAI stores the file with its original filename and MIME type. Subsequent requests using the file ID do not require MIME type detection.
Solution 6: Use a Base64-encoded data URL
If you are working with in-memory image data, you can encode the image as a Base64 string and pass it as a data URL. This is documented in source 1 for the Chat Completions and Responses APIs.
Steps:
-
Read the image file and encode it to Base64:
const fs = require('fs'); const imagePath = 'path_to_your_image.png'; const base64Image = fs.readFileSync(imagePath, 'base64'); -
For the Chat Completions API (if applicable), include the Base64 string in the request:
const completion = await openai.chat.completions.create({ model: "gpt-5.6", messages: [ { role: "user", content: [ { type: "text", text: "what's in this image?" }, { type: "image_url", image_url: { url: `data:image/png;base64,${base64Image}`, }, }, ], }, ], }); console.log(completion.choices[0].message.content); -
For the Images Edit API, the Base64 approach is not directly supported. You must use a file path or stream. However, you can write the Base64 data to a temporary file as described in Solution 3.
Why this works: The data URL explicitly specifies the MIME type (image/png), so the API does not need to infer it from the file extension.
If Nothing Works
If none of the above solutions resolve the error, consider the following escalation paths based on the sources.
Check the OpenAI Node SDK version
The GitHub issue (source 2) was reported with SDK version 4.95.0. Check if you are using an older or newer version. Update to the latest version:
npm install openai@latest
Verify the API endpoint and model
The error may occur if you are using an endpoint that does not support the image format. The official documentation (source 1) lists supported endpoints: Responses API, Chat Completions API, and Images API. Ensure you are using the correct endpoint for your use case. For image editing, use openai.images.edit with a model that supports editing (e.g., gpt-image-1).
Open an issue on the OpenAI Node SDK GitHub repository
If the error persists after trying all solutions, open a new issue at https://github.com/openai/openai-node/issues. Include:
- Your Node.js version (e.g., v22.14.0 as in source 2)
- Your OpenAI SDK version (e.g., 4.95.0)
- The exact error message
- A minimal reproducible code snippet
- The file type and size of the image you are trying to upload
Contact OpenAI support
If you have an OpenAI API account with support access, you can contact OpenAI support through the platform dashboard. Provide the same details as above.
Workaround: Use a different image format
If you are unable to fix the MIME type issue, try converting your image to a different supported format. For example, convert PNG to JPEG:
convert input.png output.jpg
Then update your code to use the JPEG file. Note that JPEG does not support transparency, so if you need transparency, stick with PNG.
How to Prevent It
To avoid this error in the future, follow these practices derived from the sources.
Always use proper file extensions
Ensure that every image file you pass to the OpenAI API has a recognized extension: .png, .jpg, .jpeg, .webp, or .gif (non-animated). This is the single most important preventive measure.
Validate file MIME type before sending
Before calling the API, verify that the file's MIME type is correct. In Node.js, you can use the file-type package:
npm install file-type
const { fileTypeFromFile } = await import('file-type');
const type = await fileTypeFromFile('path_to_your_image.png');
console.log(type.mime); // Should be 'image/png'
If the MIME type is application/octet-stream, the file may be corrupted or have an incorrect extension.
Use the Files API for repeated uploads
If you frequently upload the same images, upload them once via the Files API and reuse the file IDs. This avoids MIME type detection issues entirely.
Keep your SDK updated
Regularly update the OpenAI Node SDK to the latest version. Bug fixes related to file handling are often included in new releases.
Test with a known good image
When debugging, use a simple, small PNG file that you know works. For example, create a 100x100 pixel PNG image using an online tool or a command like:
convert -size 100x100 xc:red test.png
This eliminates variables related to image complexity or corruption.
Monitor API changes
The OpenAI API evolves rapidly. Check the official documentation (source 1) for any changes to supported file types or MIME type handling. The documentation currently lists PNG, JPEG, WEBP, and non-animated GIF as supported formats. If new formats are added, update your code accordingly.
By following these preventive measures, you can minimize the chances of encountering the Invalid file 'image': unsupported mimetype ('application/octet-stream') error in your OpenAI Node SDK applications.
The #1 Chatgpt Newsletter
The most important chatgpt updates, guides, and fixes — one weekly email.
No spam, unsubscribe anytime. Privacy policy
Sources & References
This page was researched from 3 independent sources, combined and verified for completeness.
- 1.OpenAI Documentation — VisionOfficial documentation · primary source
- 2.
- 3.Solution comment by scalex93 (1 reactions)GitHub issue
Related Error Solutions
Keep exploring ChatGPT
ChatGPT resources
Latest AI answers
Skip the manual work
Ready-made AI workflows and automation templates — import and run instead of building from scratch.