简体   繁体   English

无法使用 NodeJs/expressJs 在 Angular 8 中获取图像

[英]Unable to get Image in Angular 8 with NodeJs/expressJs

I am trying to upload image in nodejs using Multer and image upload.我正在尝试使用 Multer 和图像上传在 nodejs 中上传图像。 but while i am getting or binding images in Angular, i am getting angular router error.但是当我在 Angular 中获取或绑定图像时,我得到了 angular 路由器错误。 Angualr router listed on localhost:4200 and node router is localhost:4000 localhost:4200 上列出的 Angualr 路由器和节点路由器是 localhost:4000

Multer use in Node

var multer  = require('multer');
const storage= multer.diskStorage({
    destination:(req,file,next) => {
      next(null,'upload')
    },
    filename:(req, file,next)=> {
      next(null, file.fieldname + '-' + Date.now()+ '.' + path.extname(file.originalname))
    }
});
const upload= multer({storage:storage});
router.post('/uploadimage', upload.single('file'), function (req, res) {
  res.json(req.file); 
  console.log(req.file);
})  

TS component

UserAdd() {
    const formData = new FormData();
    formData.append('file', this.image);
    this.adminServiceService.upload(formData)
    .subscribe((res: any) => {
      this.addUser.value.image = res.filename;
      this.adminServiceService.UserAdd(this.addUser.value)
      // tslint:disable-next-line:no-shadowed-variable
      .subscribe(res => {
        console.log(res);
        swal.fire({
         position: 'center',
         icon: 'success',
         title: 'User Add',
         showConfirmButton: false,
         timer: 1500
       });
        this.router.navigate(['/jobprovider']);
     });
    });
  }

  ngOnInit() {
  }
  selectImage(event: any) {
    if (event.target.files.length > 0) {
      console.log(event.target.files);
      const file = event.target.files[0];
      this.image = file;
    }
  }

html

<div>
          <label class="col-md-4">Picture</label>
          <input type='file' formControlName="filename" (change)="selectImage($event)">

bind html

<div class="avatar" style="position: relative; top:-50px;margin-bottom:-50px">
        <img alt ="" [src]="user.filename" style="width:100px; height: 100px; max-width: 100px; max-height: 100px; border-radius: 50%; border: 5px solid rgba(240, 178,122,0.5)">
      </div>

controller for save data

exports.addJobProvider = function(req, res){

   bcrypt.hash(req.body.userPassword, saltRounds, function(err, hash){
     let user= new User({
      userName : req.body.userName,
      userEmail:req.body.userEmail,
      userPassword: hash,
      userPhone: req.body.userPhone,
      filename: req.body.image,
      role: req.body.role,
    });
    user.save()
    .then(user => {
      res.status(200).json({'user': 'Save in Database'})
    })
    .catch(err => {
      res.status(400).send('Unabale to save in Database');
    });
  })
};

error

GET http://localhost:4200/file-1574398124428..jpg 404 (Not Found)

save in mongoDB

{
    "_id": {
        "$oid": "5dd768ace336751828bcb7b4"
    },
    "active": true,
    "deleted": false,
    "userName": "A",
    "userEmail": "a@a.com",
    "userPassword": "$2a$10$mcwpbUiMi1fsi52o3hteYeDhrnlJtZsmBlPzHkEDvmJMv.t6DKcyC",
    "userPhone": 7984564564,
    "filename": "file-1574398124428..jpg",
    "role": "jobprovider",
    "__v": 0
}

I am trying to upload image in nodejs using Multer and image upload.我正在尝试使用 Multer 和图像上传在 nodejs 中上传图像。 but while i am getting or binding images in Angular, i am getting angular router error.但是当我在 Angular 中获取或绑定图像时,我得到了 angular 路由器错误。 Angualr router listed on localhost:4200 and node router is localhost:4000 localhost:4200 上列出的 Angualr 路由器和节点路由器是 localhost:4000

The problem is that you are trying to view an image that is not found, as you can see the url of the image you want to display is not correct.问题是您正在尝试查看未找到的图像,因为您可以看到要显示的图像的 url 不正确。

First we have to think about how you want to handle your files, apparently you are storing the user's image in the database directly.首先,我们必须考虑您希望如何处理文件,显然您将用户的图像直接存储在数据库中。 If so you may be able to think about saving the image in base 64 or as you prefer but currently you only store the name of the file and when you access it because it is not in the correct direction.如果是这样,您可以考虑将图像保存在 base 64 或您喜欢的格式中,但目前您只存储文件的名称以及访问它的时间,因为它的方向不正确。

In case you want to convert your image to base 64 in angular you can use this function.如果您想在 angular 中将图像转换为 base 64,您可以使用此 function。

 onImageSelect(event) { const newImage = event.target.files[0] as File; this.getBase64OfFile(newImage, (data) => { const image64 = data; }); } getBase64OfFile(file, callback) { const fr = new FileReader(); fr.addEventListener('load', (e) => { if (typeof callback === 'function') { callback(fr.result); } }); fr.readAsDataURL(file); }

Here you can get if you want only the base image 64 without the header and the file extension.如果您只想要没有 header 和文件扩展名的基本映像 64,您可以在此处获取。

 onImageSelect(event, index) { const newImage = event.target.files[0] as File; const imageName = newImage.name.split('.'); const ext = imageName[imageName.length - 1]; this.getBase64OfFile(newImage, (data) => { const image64 = data.split(',')[1]; }); } getBase64OfFile(file, callback) { const fr = new FileReader(); fr.addEventListener('load', (e) => { if (typeof callback === 'function') { callback(fr.result); } }); fr.readAsDataURL(file); }

This is a way to handle images, otherwise you could serve the images on your server and save only the name in the database.这是一种处理图像的方法,否则您可以在服务器上提供图像并仅将名称保存在数据库中。

When you want to access your images you would only have to have the address of the server where you have stored your images and add the name that you have in the database.当您想要访问您的图像时,您只需要拥有存储图像的服务器的地址并添加您在数据库中的名称。 Example:例子:

 <img *ngIf="image.image_name" [src]="environment.filesUrl + image.image_name" class="image">

In case you're going to show your images on base 64 directly in the html you can use something like this.如果您要直接在 html 中显示基于 64 位的图像,您可以使用类似的东西。

 <img *ngIf="image.image_name" [src]="'data:image/bmp;base64,' + image.image64" class="image">

You can decide how to handle your images but your mistake now is that you are accessing an address where there is no image.您可以决定如何处理您的图像,但您现在的错误是您正在访问一个没有图像的地址。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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