Error on File Upload in Angular using web API Node(Multer for image)

Viewed 38

i am trying to upload image file through web API Node (using Multer). in POSTMAN it works properly. but if i use in angular it does not work properly.

This is my API

//MULTER FOR UPLOAD IMAGE
const medicine=multer.diskStorage({
    destination:(req,file,cb)=>{
        cb(null,"../admin/src/assets/uploads/medicine");
    },
    filename: (req,file,cb)=>
    {
        cb(null,"md-"+Date.now()+file.originalname);
    }
});
const medicineUploaded=multer({
    storage:medicine
});
//MULTER FOR UPLOAD IMAGE
app.post('/addMedicines',medicineUploaded.single('imageps'),async(req,res)=>{
    //GENERATE HASH PASSWORD FROM {hashGenerate} FUNCTION
    const data=
    {
        name:req.body.name,
        companyId:req.body.companyId,
        amount:req.body.amount,
        discount:req.body.discount,
        image:req.file.filename,
        howWorks:req.body.howWorks,
        usageOfMedicine:req.body.usageOfMedicine,
        tag1:req.body.tag1,
        tag2:req.body.tag2,
        directionOfUse:req.body.directionOfUse,
        status:req.body.status,
        createdBy:req.body.createdBy,
        createdAt:Date.now()
    }
    await models.medicines.create(data).then(result=>{
        res.status(201).json({
            Code:"1",
            Message:"Medicine Created Successfully",
            Data: result
        });
    }).catch(error=>{
        res.status(500).json({
            Code:"0",
            Message:"Something went wrong",
            Post: error
        });
    })
});

this code is worked in postman but below method not working properly in angular

This is my service page:

addMedicines(data:MedicineData):Observable<any>
  {
    return  this.http.post<any>(this.URL+'addMedicines',data);
  }

This is my html page:

        <div>
            <span>Choose file</span>
            <input  type="file" (change)="onFileChange($event)" id="imageUpload" formControlName="image">
          </div>
  

This is my Component page:

onFileChange(event:any) {
    if (event.target.files.length > 0) {
      const file = event.target.files[0];
      this.medicineForm.patchValue({
        fileSource: file
      });
    }
  }

how to upload using angular?

0 Answers
Related