简体   繁体   中英

Display image on Angular 10, where image is uploaded using Multer on Node.js server

I am using MEAN stack for my web application. I am using Multer to store images in a artImages folder on Node.js server. This is post request uses Multer to upload images and store image paths with other data in MongoDB.

const storage = multer.diskStorage({
    destination: (req, file, callBack) => {
        callBack(null, 'artImages/paintings')
    },
    filename: (req, file, callBack) => {
        callBack(null, `painting&${Date.now()}&${file.originalname}`)
    }
})

var upload = multer({ storage: storage })

router.post('/', upload.array('artFileLocations'), function(req, res) {
    var paintingFileDesitnations;
    const files = req.files
    if(!files) {
        res.sendStatus(500)
    } else {
        (new Paintings({ 'paintingName': req.body.artName, 'paintingFileLocations': req.files })).save()
        .then((info) => res.send(info))
        .catch((error) => console.log(error));
    }
});

Now I am making a get request to MongoDB which gives data and file paths. Now I want to send the data as well as their respective images stored on server back to Angular. I have written this for the same:

router.get('/', function(req, res) {
    Paintings.find({})
        .then(paintings => { 
             imagePath = path.resolve(<path>, paintings[0].paintingFileLocations[0].path)
             fs.readFile(imagePath, 'utf8', function (err, data) {
               if (err) {
                   console.log(err);
               }
               console.log('Data: ', data);
               res.send(data);
            });
        })
        .catch(error => console.log(error))
});

Here, the request never consoles error, I did console data which is obviously a lot of gibberish.

On Angular client this is the response where the status says 200 but the response is HttpErrorResponse. I don't understand what is happening.

HttpErrorResponse {headers: HttpHeaders, status: 200, statusText: "OK", url: "http://localhost:8080/api/paintings/getAll", ok: false, …}
  error: {error: SyntaxError: Unexpected token � in JSON at position 0 at JSON.parse (<anonymous>) at XMLHtt…, text: "�PNG
↵↵
  IHDR??���7sRGB���8…�$�I'O$vr�:�b�*FR�B@!0(�b&�x'6��IEND�B`�"}
  headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}
  message: "Http failure during parsing for http://localhost:8080/api/paintings/getAll"
  name: "HttpErrorResponse"
  ok: false
  status: 200
  statusText: "OK"
  url: "http://localhost:8080/api/paintings/getAll"
__proto__: HttpResponseBase

Can someone help undertand and solve this problem? And give me an idea of how to display the image on Angular client? Have been stuck on this for days.

If you're using Angular's HttpClient , the default responseType is json - you might want to choose blob

responseType?: "arraybuffer" | "blob" | "text" | "json"

See the overloads of the HttpClient get request

The call would be something like:

return this.httpClient.get(url, {responseType:'blob'});

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