Magento – MIME type not valid when uploading image using REST API

apiimage-uploadmagento2product-images

I'm trying to set a product image using the web api by POSTing to this url:

http://my_magento_server/rest/V1/products/my-url-key/media

With the following content:

{"entry":
  {
    "media_type": "image",
    "label": "Image",
    "position": 1,
    "disabled": false,
    "types": [
      "image",
      "small_image",
      "thumbnail"
    ],
    "file": "/m/b/mb01-blue-0.jpg",
    "content": {
      "base64EncodedData": "iVBORw0KGgoAAAANSUhEUgAAACgAAAAoCAYAAACM/rhtAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAWtJREFUeNpi/P//P8NgBkwMgxyMOnDUgTDAyMhIDNYF4vNA/B+IDwCxHLoakgEoFxODiQRXQUYi4e3k2gfDjMRajsP3zED8F8pmA+JvUDEYeArEMugOpFcanA/Ef6A0CPwC4uNoag5SnAjJjGI2tKhkg4rLAfFGIH4IxEuBWIjSKKYkDfZCHddLiwChVhokK8YGohwEZYy3aBmEKmDEhOCgreomo+VmZHxsMEQxIc2MAx3FO/DI3RxMmQTZkI9ALDCaSUYdOOrAIeRAPzQ+PxCHUM2FFDb5paGNBPRa5C20bUhxc4sSB4JaLnvxVHWHsbVu6OnACjyOg+HqgXKgGRD/JMKBoD6LDb0dyAPE94hwHAw/hGYcujlwEQmOg+EV9HJgLBmOg+FMWjsQVKR8psCBoDSrQqoDSSmoG6Hpj1wA6ju30LI9+BBX4UsC+Ai0T4BWVd1EIL5PgeO+APECmoXgaGtm1IE0AgABBgAJAICuV8dAUAAAAABJRU5ErkJggg==",
      "type": "image/jpeg",
      "name": "new image"
    }
  }
}

But I get 400 response:

The image MIME type is not valid or not supported

Any idea how I can upload a file as product image in Magento 2?

Best Answer

After base64 decoding the image you provided, I noticed it is the PNG image, not JPEG.

Try changing the "type" attribute in your JSON to "image/png".

Additionally, you should add file extension to your "name" attribute.

The example below worked fine for me.

{
        "entry": {
            "media_type": "image",
            "label": "Image",
            "position": 1,
            "disabled": false,
            "types": [
                "image",
                "small_image",
                "thumbnail"
            ],
            "file": "/m/b/mb01-blue-0.png",
            "content": {
                "base64EncodedData": "iVBORw0KGgoAAAANSUhEUgAAACgAAAAoCAYAAACM/rhtAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAWtJREFUeNpi/P//P8NgBkwMgxyMOnDUgTDAyMhIDNYF4vNA/B+IDwCxHLoakgEoFxODiQRXQUYi4e3k2gfDjMRajsP3zED8F8pmA+JvUDEYeArEMugOpFcanA/Ef6A0CPwC4uNoag5SnAjJjGI2tKhkg4rLAfFGIH4IxEuBWIjSKKYkDfZCHddLiwChVhokK8YGohwEZYy3aBmEKmDEhOCgreomo+VmZHxsMEQxIc2MAx3FO/DI3RxMmQTZkI9ALDCaSUYdOOrAIeRAPzQ+PxCHUM2FFDb5paGNBPRa5C20bUhxc4sSB4JaLnvxVHWHsbVu6OnACjyOg+HqgXKgGRD/JMKBoD6LDb0dyAPE94hwHAw/hGYcujlwEQmOg+EV9HJgLBmOg+FMWjsQVKR8psCBoDSrQqoDSSmoG6Hpj1wA6ju30LI9+BBX4UsC+Ai0T4BWVd1EIL5PgeO+APECmoXgaGtm1IE0AgABBgAJAICuV8dAUAAAAABJRU5ErkJggg==",
                "type": "image/png",
                "name": "new_image.png"
            }
        }
    }
Related Topic