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>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…