Jump to content

Webservice API: Axios POST image upload 400 Error


vleungz

Recommended Posts

When I try to make an axios post request to upload a product image using the endpoint '/api/images/products/id', I get a

400 error: Please set an "image" parameter with image data for value.

Here's the snippet of the code i have.

const form = new FormData()
const image = await axios.get(image_url, {responseType: 'stream'})
const fileName = 'image.png'
form.append('image', image.data, fileName)
const headers = {...form.getHeaders(), Authorization: 'Basic ${key}'}
const imageData = 
      await axios.post(`https://presta-fair.net/api/images/products/${id}`, form, {headers})

Any help would be greatly appreciated. Thanks!

Link to comment
Share on other sites

  • 1 year later...
6 minutes ago, Nickz said:

more details get you more answers.

Hi !

To be honest it was really the same kind of code. But i just made it works! 

If some other people need to try sending a post request with image from node.js to prestashop, here is a working example:

const FormData = require("form-data");
const fs = require("fs");
const axios = require("axios");

// Read the image file into a buffer
const imageBuffer = fs.readFileSync("image.jpg");

// Create a FormData object
const form = new FormData();

// Append the image buffer to the form data
form.append("image", imageBuffer, "image.jpg");

// Make an HTTP POST request to the PrestaShop API
axios
  .post("https://example.com/api/images/products/15924", form, {
    params: {
      ws_key: "EXAMPLE",
    },
    headers: {
      ...form.getHeaders(),
      "Content-Length": form.getLengthSync(),
    },
  })
  .then((response) => {
    console.log(response);
  })
  .catch((error) => {
    console.error(error.response.data);
  });

So, what was missing in my case (and in case of @vleungz one year ago) was to add to the headers the size with:

"Content-Length": form.getLengthSync()

It's also mandatory to have the filename as third parameter of the formData append function.

It was the 2 parts missing for me. Without theses, PHP don't receive anything in the $_FILES variable.

Hope that can helps some other!

Edited by Jerome38190
small precision (see edit history)
  • Like 1
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...