Search code examples
javascripttypescriptcorsangular6multer

"fake path" issue using multer+angular 6


I spend the last 3 days to fix the problem , but i didnt figure out yet the issue.

Angular CLI: 6.0.8

Node: 8.11.2

OS: win32 x64

Angular: 6.0.6

multer. 1.3.1

my code at "childApi" using multer staff :

var store = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, './uploads');
    },
    filename: function (req, file, cb) {
        cb(null, Date.now() + '.' + file.originalname);
    }
});

var upload = multer({ storage: store , }).single('file');

router.post('/upload', function (req, res, next) {
    upload(req, res, function (err) {
        if (err) {
            return console.log ('not working well')
        }
        //do all database record saving activity
        return res.json({ originalname: req.file.originalname, uploadname: req.file.filename });
    });
});

my code at "add-child" component using simple code :

import { Component, OnInit, Inject } from '@angular/core';

import { ActivatedRoute, Router } from '@angular/router';
import { MatDialog, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material';
import { Child } from '../../models/child';
import { ChildService } from '../../services/child.service';
import {FileUploader } from 'ng2-file-upload';

const uri = 'http://localhost:3000/childApi/upload';


@Component({
  selector: 'app-add-child',
  templateUrl: './add-child.component.html',
  styleUrls: ['./add-child.component.css']
})

export class AddChildComponent implements OnInit {
    newChild = new Child;
    uploader: FileUploader = new FileUploader({ url: uri });
    attachmentList: any = [];


  constructor(private childService: ChildService, 
    private route: ActivatedRoute, 
    private router: Router, 
    public dialogRef: MatDialogRef<AddChildComponent>,
    @Inject(MAT_DIALOG_DATA) public data: any) { 


      this.uploader.onCompleteItem = (item: any, response: any, status: any, headers: any) => {
          this.attachmentList.push(JSON.parse(response));
      };
    }

The problem is that after I upload the file to the folder "uploads" ,I want to display my new photo on the screen.

The console give me this error :

GET unsafe:C:\fakepath\child+thinking.jpg 0 ()

If someone help its will be amazing.

Thanks...


Solution

  • I figure out what to do , I just put this sentences inside my code at "add-child" component using :

    this.uploader.onCompleteItem = (item: any, response: any, status: any, headers: any) => {
            this.newChild.user_img = JSON.parse(response).uploadname;
            this.attachmentList.push(JSON.parse(response));
        };
    }