使用Angular和Node.js将多个图像上传到AWS

时间:2020-07-01 01:59:15

标签: node.js amazon-web-services multer angular9

我正在将多个图像上传到一个AWS存储桶,然后将其作为URL发送,该URL将使用mongoose,Node.js,multer和Angular 9作为前端保存在我的mongodb中。图片没有上传,发送获取请求时,我的图片为空。先感谢您 下面是我的angular.ts代码

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { FormGroup, FormControl, Validators} from '@angular/forms';
import { ImagesService} from '../images.service';
import { Router } from '@angular/router';
import { DataService} from '../../product/data.service'


@Component({
  selector: 'app-admin-project',
  templateUrl: './admin-project.component.html',
  styleUrls: ['./admin-project.component.css']
})
export class AdminProjectComponent implements OnInit {
  images = [];
  myForm = new FormGroup({
   name: new FormControl('', [Validators.required, Validators.minLength(3)]),
   file: new FormControl('', [Validators.required]),
   fileSource: new FormControl('', [Validators.required])
 });



  

 constructor(private http: HttpClient, private image: ImagesService, private router: Router, private data: DataService) { }
  
 async ngOnInit() {
}

 get f(){
   return this.myForm.controls;
 }
  
 onFileChange(event) {
   if (event.target.files && event.target.files[0]) {
       var filesAmount = event.target.files.length;
       for (let i = 0; i < filesAmount; i++) {
               var reader = new FileReader();
  
               reader.onload = (event:any) => {
                 console.log(event.target.result);
                  this.images.push(event.target.result); 
  
                  this.myForm.patchValue({
                     fileSource: this.images
                  });
               }
 
               reader.readAsDataURL(event.target.files[i]);
       }
   }
 }

   
 async submit(){
  
    try {
      
       
  console.log(this.myForm.value);
 const data = await this.image.post(
  'http://localhost:8000/api/images',
  this.myForm.value
); console.log('this.project');
data['success']
  ? this.router.navigate(['/projects'])
    .then(() => this.data.success(data['message']))
    .catch(error => this.data.error(error))
  : this.data.error(data['message']);
 
  } catch (error) {
    this.data.error(error['message']);
        }
        
    }
}

和下面的我的node.js路由器代码

const router = require('express').Router();
const async = require('async');
const Image = require('../models/imageModels');
const fs = require ('fs');
const aws = require('aws-sdk');
const multer = require('multer');
const multerS3 = require('multer-s3');
const s3 = new aws.S3( );




aws.config.update({
  secretAccessKey: "secretAccessKey",
  accessKeyId: "accessKeyId",
  region: "eu-west-1"
});
//function to upload resources to AWS using multer service 
var upload = multer({
  storage: multerS3({
    s3: s3,
    acl: 'public-read',
    bucket: 'carnelian-project-app1',
    metadata: function (req, file, cb) {
              console.log(file);
      cb(null, {fieldName: file.fieldname});
    },
    key: function (req, file, cb) {
      cb(null, Date.now().toString())
    }
  })
}).array('file');

router.post("/images",upload,
(req, res, next) => {
  let  = new Image();
  myForm.name = req.body.name;
  myForm.file = req.files;
  myForm.save();
  res.json({
    success: true,
    message: 'Successfully Added the project'
  });
});


router.get("/images", (req, res, next) => {
    Image.find({}, (err, projects) => {
     res.json({
       success: true,
       message: "Success",
       projects: projects
     })
    });
  })
 

   router.delete("/images/:id",  (req, res, next) => {
    Image.findByIdAndDelete({ _id: req.params.id  })
      .exec((err, project) => {
        if (err) {
          res.json({
            success: false,
            message: 'Project not deleted'
          });
        } else {
          if (project) {
            res.json({
              success: true,
              project: project,
              message: 'Project Successfully Deleted'
            });
          }
        }
      });
  });
 

    
  router.get('/images/:id', (req, res, next) => {
    Image.findById({ _id: req.params.id })
    
      .exec((err, project) => {
        if (err) {
          res.json({
            success: false,
            message: 'Images are not found'
          });
        } else {
          if (project) {
            res.json(
               project
            );
          }
        }
      });
  });

//Exporting the module 
module.exports = router;

0 个答案:

没有答案