0

I am trying to upload an array of images using my custom API (Node JavaScript), here I just want to save the file name to my database, and uploading of the file works just fine (the middleware which I created for uploading works just fine because I have tried using the same middleware in the postman).

When it comes to the actual JavaScript file it is not working and shows the following error:

Cast to string failed for value "{ '0': {}, '1': {} }" at path "images", images: Cast to Array failed for value "[ { '0': {}, '1': {} } ]" at path "images"

Here is my code

const createProperty = ['city', 'propertyType', 'propertyName', 'images'];

const newProperty = new Array();
for (var i = 0; i < myids.length; i++) {
  newProperty[i] = $(myids[i]).val();
}


newProperty[myids.length] = [document.getElementById('PropertyPhotos').files];

const data = {};
createProperty.forEach((id, index) => {
  data[createProperty[index]] = newProperty[index]
})


await createData(data);

// here is the CreateDate function

export const createData = async (data) => {
  try {
    const res = await axios({
      method: 'POST',
      url: '/api/v1/properties',
      data
    });

    if (res.data.status === 'success') {
      showAlert('success', 'Property Created Successfully');
    }
    console.log(res.data);
  } catch (err) {
    showAlert('error', err.response.data.message);
    console.log(err.response.data.message);
  }
}        
3
  • i think you should use JSON.stringify to cast the object to an String. Commented Dec 15, 2020 at 8:13
  • What is the value of newProperty and document.getElementById('PropertyPhotos').files? Do you want to insert / copy the image files and get a 2d array from it? Please use console logs or a debugger to identify where the issue arise and post the expected behavior of the code Commented Dec 15, 2020 at 8:35
  • what's in myids at athe time of iteration? Please show it in your code. Commented Dec 15, 2020 at 8:37

1 Answer 1

0

It looks like you are using Mongo. Look here and here.

And to send files you need to use form-data, but I don't see it in your code.

const formdata = new FormData();

formdata.append("file", fileInput.files[0], "/filepath.pdf");
Sign up to request clarification or add additional context in comments.

2 Comments

hello, i don't know but whenever i use formdata, my above function createData is not working like it is giving me null as data.. please help me with that
@AshishArjun show full code for data transfer on front and back

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.