1

i'm trying to send image in form data to API node.js server but it's give me error every time console.log(fd.getAll('image')[0])

it came with correct File,

here's my HTML code

<form @submit.prevent>
<input type="text" placeholder="اسم القسم" v-model="name">
<input type="file" @change="fileSelected">
<button @click="addCategory" class="button--edit">اضف قسم جديد</button>
</form>

javascript code :

fileSelected(event){
  this.selectedFile = event.target.files[0]
},
addCategory(){
 const token = this.$store.state.idToken.token;
 const file = this.selectedFile;
 const fd = new FormData();
 const name = this.name
 fd.append('image', file); 
 //console.log(fd.getAll('image')[0])
    axios({
        method: 'post',
        url: '/admin/support/catigory',
        data: {
          image: fd,
          name: name
        },
        headers: {
        'Authorization': `Basic ${token}`,
        }
    })
    .then(res => {
        console.log(res)
    })
    .catch(err => {
      console.log(err.response)
    })
}

here is the back-end function :

exports.postRoute = async (req, res, next) => {
const name = req.body.name;
const image = req.files;  
const errors = validationResult(req);
  try {
if (!errors.isEmpty()) {
const error = new Error(
`validation faild for ${errors.array()[0].param} in the ${
errors.array()[0].location
}`
);
error.statusCode = 422;
throw error;
}
if (image.length == 0) {
const error = new Error("validation faild.. you should insert image");
error.statusCode = 422;
throw error;
 }

here is the error: error in console

also i had tried to add :

'Content-Type': `multipart/form-data` to the herders but nothing changed
5
  • Append name to your FormData instance (fd.append('name', name)) and send that as the request payload, ie data: fd. Also, do not set a Content-Type header. Your browser will do this automatically for you when you POST a FormData instance Commented Jul 2, 2020 at 0:14
  • 1
    Does this answer your question? Send FormData object AND an additional parameter via ajax. I know it's about jQuery but the solution is the same Commented Jul 2, 2020 at 0:17
  • i've tried to append name but also it became empty object in the body of request code : fd.append('image', file); fd.append('name', name); axios({ method: 'post', url: '/admin/support/catigory', data: { fd }, headers: { 'Authorization': Basic ${token}, } }) Commented Jul 2, 2020 at 0:33
  • 1
    No, not data: { fd }, data: fd. You can also use the shorter version axios.post('/admin/support/catigory', fd, { headers: { Authorization: `Basic ${token}` } }) Commented Jul 2, 2020 at 0:35
  • it worked. thank you so much Commented Jul 2, 2020 at 0:44

0

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.