将图片和Json从Angular上传到Multer / Express

时间:2018-02-06 21:15:54

标签: node.js angular image upload multer

我想使用Express和Multer将图像和json上传到服务器。 当我使用Postman进行测试时没有问题但是当我在Angular中测试前端时,似乎没有发送图像。

以下是代码:

问题form.component.html

<div class="problemContainer">
 <div class="problemForm">
  <h2>Soumission de problème</h2>
  <form [formGroup]="form" (ngSubmit)="submitForm()">
    <p>
      <mat-form-field class="inputFW">
        <input matInput formControlName="User" placeholder="Adresse email">
        <mat-error>This field is required</mat-error>
      </mat-form-field>
    </p>
    <p>
      <mat-form-field class="inputFW">
        <input matInput value="{{machineName}}" placeholder="Nom de la machine" disabled>
        <mat-error>Le nom de la machine est requis</mat-error>
      </mat-form-field>
    </p>
    <p>
      <mat-form-field class="inputFW">
        <textarea matInput placeholder="Description du problème (max 200 caractères)" formControlName="Description" rows="3"></textarea>
      </mat-form-field>
    </p>
    <p>
      <label>Image (Optionnel)</label><br><br>
      <input type="file" (change)="fileChange($event)" name="image" />
    </p>
    <button mat-raised-button color="primary">Envoyer</button>
  </form>
 </div>

在调用服务的组件中起作用

submitForm(){
  if(this.form.valid){
    let obj = this.form.value
    obj.image = this.image
    this.service.createProblem(obj).subscribe(data => console.log(data), err => {console.log(err)})
  }else{
    console.log("erreur")
  }
}

在发布到服务器的服务中起作用

createProblem(problem: Object){
  console.log('roman')
  let form = new FormData()
  form.append('Name', problem['Name'])
  form.append('Description', problem['Description'])
  form.append('User', problem['User'])
  form.append('image', problem['image'])
  console.log(problem['image'])
  return this.http.post(getUrl()+ `problems`, form);
}

multer的配置

let storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, 'images')
  },
  filename: function (req, file, cb) {
    cb(null, 'problem_' + Date.now()+'.'+mime.extension(file.mimetype))
  }
})
let upload = multer({ storage: storage });

在控制器中调用函数的路径

router.route('/')
/** GET /api/problems - Get list of Problems */
  .get(pbCtrl.list)

/** POST /api/problem - create a new problem */
  .post(/*validate(paramValidation.problem), */upload.single('image'), pbCtrl.create);

控制器中的功能

function create(req, res, next) {
  let photo
  if(req.file != null)
    photo = req.file.filename
  PC.findOne({ Name: req.body.Name, Active: true }, { '_id': 0 }).exec()
    .then((pc) => {
        if (pc == null)
            return res.sendStatus(400)
        const newPc = new PC({
            Name: pc.Name,
            Local: pc.Local,
            IP: pc.IP,
            MAC: pc.MAC,
            Comment: pc.Comment,
            Active: pc.Active,
            Problem: { User: req.body.User, Description: req.body.Description, Image: photo }
        })
        newPc.save()
            .then(savedPC => {
                res.json(savedPC);
                //return next();
            }).catch(e => { next(e); });;

    })
    .catch((err) => {
        console.log(err)
        res.sendStatus(400)
    })
}

全部谢谢

1 个答案:

答案 0 :(得分:0)

解决

加载文件的功能

fileChange($event) {
  let reader = new FileReader();
  if($event.target.files && $event.target.files.length > 0) {
    let file = $event.target.files[0];
    this.file = file
  }
}

提交表单的功能

submitForm(){
  if(this.form.valid){
    let obj = this.form.value
    obj.image = this.file
    this.service.createProblem(obj).subscribe(data =>     this.openSnackBar('Votre demande a bien été enregistrée'), err =>   {console.log(err)})
  }else{
    console.log("erreur")
  }
}

在服务中发挥功能

createProblem(problem: Object){
  let form = new FormData()
  form.append('Name', problem['Name'])
  form.append('Description', problem['Description'])
  form.append('User', problem['User'])
  form.append('image', problem['image'])
  return this.http.post(getUrl()+ `problems`, form).map((res) => {
    return res.json()
  });
}