简体   繁体   中英

How to save file from an Express app/Angular form using Multer

I've create an API to save in the server an image uploaded and works succesfully in postman. In my Angular frontend form seems that the image is not sended and in router upload-image the req.file is empty. In controller I'm first saving the post and after saving the image (I wanted to set a name to the uploaded file with the post id, but that's not possible) Can you help me? Thank you!

Form

  <form class="login-form" (submit)="formSubmit();" enctype="multipart/form-data">
                    <div class="col-md-3"></div>
                    <div class="col-md-6 ">
                        <div class="ec-alert bg-danger" *ngIf="formError">
                            {{ formError }}
                        </div>
                        <div class="form-group ">
                            <input id="title" class="form-control" placeholder="Titolo" type="text" name="username" [(ngModel)]="postTitle" required>
                        </div>
                        <div class="form-group ">
                            <textarea id="content" class="form-control" placeholder="Contenuto" name="content" [(ngModel)]="postContent" required></textarea>
                        </div>
            <div class="form-group ">
                            <input id="image" type="file" name="image" required (change)="onChange($event)">
                        </div>
                        <div class="form-group">
                            <input class="btn btn-primary btn-lg" value="Conferma" type="submit">
                        </div>
                    </div>
                </form>

CreatePostComponent.ts

public formSubmit() {
    this.formError = "";

    if(
        !this.postTitle ||
        !this.postContent
    ) {
        return this.formError = "Devi compilare entrambi i campi.";
    }

    if(!this.formError) {
        this.createPost();
    }

    return 0;
}

private createPost() {
    let requestObject = {
        method: "POST",
        location: "admin/create-post",
        body: {
            title: this.postTitle,
            content: this.postContent,
            image: this.postImage
        }
    }

    this.api.makeRequest(requestObject).then((val:any) => {
        if(val) {
    this.saveImage();

        }
    });
}

public onChange(event:any) {
    this.postImage = event.target.files[0];
}


public saveImage() {

    let requestObject = {
      method: "POST",
      location: "admin/upload-image",
      image: this.postImage
    }

    this.api.makeRequest(requestObject).then((val:any) => {
      console.log(val);
      if(val) {

      }
    });

  }

Router.js (Express)

router.post('/create-post', ({body, payload}, res) {

    if(!body.content || !body.title) {
        return res.statusJson(400, { message: "I dati inviati con la richiesta sono insufficienti." });
    }
    const post = new Post();

    post.title = body.title;
    post.content = body.content;

    post.save((err) => {
        if(err) { return res.json({ err: err }); }
        return res.statusJson(201, { message: "Post creato." });
    });
});

router.post('/upload-image', upload.single('image'), (req, res) => {
    console.log(req.file);
  if (!req.file) {
    console.log("No file received");
    return res.send({
      success: false
    });

  } else {
    console.log('file received');
    return res.send({
      success: true
    })
  }
});

It seems like a CORS issue. Do one thing, add these headers to your requests, or add these to your interceptors: for a separate request:

    var myHeaders = new Headers();
    myHeaders.append("Access-Control-Allow-Headers": "*");
    myHeaders.append("Access-Control-Allow-Methods": "*");  // in case its a method issue

    let requestObject = {
      method: "POST",
      headers: myHeaders
      location: "admin/upload-image",
      image: this.postImage
    }

for interceptors:

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
      request = request.clone({
          setHeaders: {
            'Access-Control-Allow-Origin': '*',
          }
        });
}

MDN headers: https://developer.mozilla.org/en-US/docs/Web/API/Request/headers

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM