通过Angular表单上传文件

时间:2019-11-18 16:46:27

标签: angular mongodb file-upload angular-forms

我正在Angular 9项目中工作,是一个CRUD,它已经将其连接到mongo数据库,一切工作正常,我完美地添加了任务,但是我决定添加一个输入来上传图像,但这让我很难受。我将显示前端代码,然后将显示后端代码。

查看(HTML):

<div class="container">
  <div class="row">

    <div class="col s5">
      <div class="card">
        <div class="card content">
          <form #employeeForm="ngForm" (ngSubmit)="addEmployee(employeeForm)">
            <input type="hidden" name="_id" #_id="ngModel" [(ngModel)]="employeeService.selectedEmployee._id">
            <div class="row">
                <div class="input-field col s12">
                  <input type="text" name="name" #name="ngModel" [(ngModel)]="employeeService.selectedEmployee.name" placeholder="Enter your name">
                </div>
                <div class="input-field col s12">
                    <input type="text" name="position" #position="ngModel" [(ngModel)]="employeeService.selectedEmployee.position" placeholder="Enter your position">
                </div>
                <div class="input-field col s12">
                    <input type="text" name="office" #office="ngModel" [(ngModel)]="employeeService.selectedEmployee.office" placeholder="Enter your office">
                </div>
                <div class="input-field col s12">
                    <input type="text" name="salary" #salary="ngModel" [(ngModel)]="employeeService.selectedEmployee.salary" placeholder="Enter your salary">
                </div>
                <div class="input-field col s12">
                    <input type="file" name="productImage" #productImage accept="image/*" [(ngModel)]="employeeService.selectedEmployee.productImage" (change)="onFileSelected($event)">
                    <button type="button" (click)="onUpload()">Upload</button>
                </div>
                <div class="card-action">
                  <div class="input-field col s12">
                    <button class="btn right" style="margin-left:0.5em;" (click)="resetForm(employeeForm)">
                      CANCEL
                    </button>
                    <button type="submit" class="btn right">
                      SAVE
                    </button>
                  </div>
                </div>
            </div>
          </form>
        </div>
      </div>
    </div>

employees.component.ts:

onFileSelected(event) {
  const productImage = event.target.files[0];
  return productImage;
}

addEmployee(form: NgForm, event) {
    if(form.value._id) {
      this.employeeService.putEmployee(form.value)
        .subscribe(res => {
          this.resetForm(form);
          M.toast({html: 'Edited successfuly'});
          this.getEmployees();
        });
      } else {
        this.employeeService.postEmployee(form.value)
          .subscribe(res => {
            this.resetForm(form);
            M.toast({html: 'Saved successfuly'});
            this.getEmployees();

          });
      }
  }

employee.ts(模型):

export class Employee {
  _id: string;
  name: string;
  position: string;
  office: string;
  salary: number;
  productImage: string;

  constructor(_id = '', name = '', position = '', office = '', salary = 0, productImage = '') {
    this._id = _id;
    this.name = name;
    this.position = position;
    this.office = office;
    this.salary = salary;
    this.productImage = productImage;
  }
}

以及我的BACKEND。

employee.controller.js

const Employee = require('../models/employee');
const employeeCtrl = {};

employeeCtrl.createEmployee = async (req, res) => {
    const employee = new Employee({
        name: req.body.name,
        position: req.body.position,
        office: req.body.office,
        salary: req.body.salary,
        productImage: req.file
    });
    await employee.save();
    res.json({
        'status': 'employee saved'
    })

};

employee.routes.js:

const express = require('express');
const router = express.Router();
const multer = require('multer');
const storage = multer.diskStorage({
    destination: function(req, file, cb){
        cb(null, 'uploads/');
    },
    filename : function(req, file, cb){
        cb(null, file.originalname);
    }
});
const fileFilter = (req, file, cb) => {
    //reject a file
    if(file.mimetype === 'image/jpeg' || file.mimetype === 'image/png'){
        cb(null, true);
    } else {
        cb(new Error('The file you are trying to upload is not a image'), false);
    }
}
const upload = multer({
    storage: storage, 
    limits: {
        fileSize: 1024 * 1024 * 5
    },
    fileFilter: fileFilter
});
const subida = upload.single('productImage');
const employee = require('../controllers/employee.controller');
router.get('/', employee.getEmployees);
router.post('/', subida, employee.createEmployee);
router.get('/:id', employee.getEmployee);
router.put('/:id', employee.editEmployee);
router.delete('/:id', employee.deleteEmployee);
module.exports = router;

index.js

const express = require('express');
const morgan = require('morgan');
const cors = require('cors');
const app = express();

const { mongoose } = require('./database');

// Settings
app.set('port', process.env.PORT || 3000);


// Middlewares
app.use('/uploads', express.static('uploads'));
app.use(morgan('dev'));
app.use(express.json());
app.use(cors({origin: 'http://localhost:4200'}));

// Routes
app.use('/api/employees', require('./routes/employee.routes'));

// Starting the server
app.listen(app.get('port'), () => {
    console.log('server on port', app.get('port'));
});

我在服务器中遇到的错误是它找不到productImage路径。但我不知道该如何获取,将其发送到服务器以节省员工。员工可以完美地保存自己的形象。图片无法正常显示。

请帮助我的人或指导我,因为我是新手。

亲切的问候。

1 个答案:

答案 0 :(得分:0)

尝试一下,它在具有较小图像(不是MB大小)的当前项目中对我有用:

featureImage: string;

onFileSelected(event) {
    let _t = this;
    var reader  = new FileReader();
    this.uploadedFiles = event;

    reader.addEventListener("load", function () {
        _t.featureImage = reader.result;
    }, false);

    if (event) {
        reader.readAsDataURL(this.uploadedFiles[0]);
    }
}

这会将图像转换为存储在变量featureImage中的base64字符串,然后在提交表单时,您只需将其添加到表单中。

submit(form) {
    ...
    form.productImage = this.featureImage;
    ...
}