Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
293 views
in Technique[技术] by (71.8m points)

node.js - How can I upload an image to mongodb using multer module

I'm new to nodeJs and I'm trying to upload an image to MongoDB through multer module. The backend server image.js works fine when I test through postman. But when I want to upload an image from the front end I couldn't. Any possible suggestion for this.

This is image.js

let express = require("express");
let app =express();
let mongodb = require("mongodb");
let assert = require("assert");
let createClient = mongodb.MongoClient;
let dbUrl = "mongodb://127.0.0.1:27017/images";
let multer = require("multer");


let storage = multer.diskStorage({
    destination:(req,file,cb)=>{
        cb(null,'images');
    },
    filename:(req,file,cb)=>{
        cb(null,file.fieldname+'_'+Date.now()+'.jpg')
    }
});
let upload = multer({storage:storage});

let imageup = express.Router().post('/',upload.single('image'),(req,res)=>{
    createClient.connect(dbUrl,(err,db)=>{
        assert.deepStrictEqual(null,err);
        insertDocuments(db,'images'+req.file.filename,()=>{
            db.close();
            res.json({'message':"file upladed successfully"});
        })
    })
})
let insertDocuments = function(db,filepath,callback){
    let collection = db.collection('users');
    collection.insertOne({filepath:filepath},
    (err,result)=>{
        //.deepStrictEqual(err,result);
        callback(result);
    });
}

module.exports = imageup;

This is server.js file,

let express = require("express");
let app = express();
let port = 8080;
app.listen(port);

app.use('/imageup',require("./image"));

console.log(`server listening to port ${port}`)

This is service.ts

import { Injectable } from "@angular/core";
import { HttpClient } from "@angular/common/http";
import { Observable } from "rxjs";

@Injectable({
    providedIn:'root'
})

export class imageupService{
    constructor(public http:HttpClient){}
    public imageupload(data:any):Observable<any>{
        return this.http.post("http://localhost:8080/imageup",data)
    }
}

This is image.component.ts file

import { Component, OnInit } from '@angular/core';
import { HttpErrorResponse } from "@angular/common/http";
import { imageupService } from "../services/imageupservice";
@Component({
  selector: 'imageup',
  templateUrl: './imageup.component.html',
  styleUrls: ['./imageup.component.css']
})
export class ImageupComponent implements OnInit {

  public file:any;
  constructor(public service:imageupService) { }
  public saveimage(data:any){
    this.service.imageupload(data).subscribe((posRes)=>{
      if(posRes.message =="file upladed successfully")
      {
        console.log("File uploaded successfully");
      }
    })
  }

  ngOnInit(): void {
  }

}

This is HTML file

<p>Upload Image</p>
<input type="file" name="image" id="image" [(ngModel)]="file">
<button (click)="saveimage({'filepath':file})">Upload</button>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Storing the binary of an image directly in MongoDB is a really bad choice.

This practice eats up your storage space really quickly and the queries will be very slow.

Multer is designed in a way that allows you to upload the file to a storage local (the server itself) / remote (e.g. AWS S3). What you should do is to store the URL (for remote storage) or the path (local: like any static assets [css, js]) in MongoDB instead of the image as a whole.

You should then render the image on your page using the URL to the remote storage (e.g. https://bucketname.s3.region.amazonaws.com/you_image.jpg)

or your server (https://yousite.com/assets/your_image.jpg)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...