如何在同一路径中将图像与其他数据一起发送

时间:2019-05-30 16:55:16

标签: node.js angular multer

我想发送询问表格以及学生图像。通过使用multer在后端,我能够将图像存储在数据库中。但是在前端,我无法将图像和其他学生数据一起以相同的方式发送到后端,请为此提供帮助。后端工作正常,我能够保存图像。但是我无法从前端保存图像到后端

registation.component.html

     <h1 class="page-header">Student Enquiry Form</h1>

<!-- Custom Success/Error Message -->
<div class="row show-hide-message">
  <div [ngClass]="messageClass">
    {{ message }}
  </div>
</div>



<div class="example-container">
    <form class="example-container" [formGroup]="form" (ngSubmit)="onSubmit()">
  <mat-form-field>
   <input matInput placeholder="Enter your email" formControlName="email" >
   <mat-error *ngIf="form.controls['email'].errors?.email && !form.controls['email'].errors?.required">
      Please enter a valid email address
    </mat-error>
    <mat-error *ngIf="form.controls['email'].errors?.required">
      Email is <strong>required</strong>
    </mat-error>
     </mat-form-field>

  <mat-form-field>
    <input matInput placeholder="Enter your fullname" formControlName="fullName" required>

  </mat-form-field>

  <mat-form-field>
    <input matInput placeholder="Enter your fathername" formControlName="fatherName" required>
  </mat-form-field>

  <mat-form-field>
    <input matInput placeholder="Enter your mothername" formControlName="motherName" required>
  </mat-form-field>

<mat-form-field>
  <input  matInput placeholder="Enter your mobilenumber" type="number" formControlName="mobilenumber" required>
</mat-form-field>

<label>Gender: </label>
      <mat-radio-group formControlName="Gender">
        <mat-radio-button value="male">Male</mat-radio-button>
        <mat-radio-button value="female">Female</mat-radio-button>
        <mat-radio-button value="others">Others</mat-radio-button>
      </mat-radio-group>

  <mat-form-field>
    <textarea matInput placeholder="Textarea"></textarea>
  </mat-form-field>

  <mat-form-field>
    <mat-select placeholder="Select">
      <mat-option value="option">Option</mat-option>
      <mat-option value="AI">AI</mat-option>
      <mat-option value="IOT">IOT</mat-option>
      <mat-option value="BlockChain">BlockChain</mat-option>
    </mat-select>
  </mat-form-field>

  <input type="file" capture="camera" accept="image/*" name="file" (change)="onFileSelected($event)">
  <button type="button" (click)="onUpload()">Upload File</button>

<div class="example-button-row">
  <button type="submit" mat-button color="warn">Register</button>
</div>

</form>

register.component.ts

import { Component, OnInit } from '@angular/core';
import { FormControl, Validators, FormBuilder, FormGroup } from "@angular/forms";
import { Router } from '@angular/router';
import { StudentService } from '../Services/student.service';
import { combineLatest } from 'rxjs';

@Component({
  selector: 'app-register',
  templateUrl: './register.component.html',
  styleUrls: ['./register.component.css']
})
export class RegisterComponent implements OnInit {
  form: FormGroup;
  messageClass;
  message;
  studentDetails: any={};
  selectedFile = null;

  imageUploaded: any;
   constructor(
    private formBuilder: FormBuilder,
    private router: Router,
    private studentService: StudentService
  ) { 
    this.createForm();
  }

  createForm(){
    this.form = this.formBuilder.group({
      email : ['', Validators.compose([
         Validators.required, Validators.email,
      ])],
      fullName:['', Validators.compose([
        Validators.required
      ])],
      fatherName:['', Validators.compose([
        Validators.required
      ])],
      motherName: ['',Validators.compose([
        Validators.required
      ])],
      mobilenumber: ['',Validators.compose([
        Validators.required
      ])],
      Gender: ['', Validators.compose([
        Validators.required
      ])]



    })

  }

  onSubmit(){
    const student = {
      email: this.form.get('email').value,
      fullName: this.form.get('fullName').value,
      motherName: this.form.get('motherName').value,
      fatherName: this.form.get('fatherName').value,
      mobilenumber: this.form.get('mobilenumber').value,
    file: this.selectedFile
    }
this.studentService.getDetails(student).subscribe(data =>{
     this.studentDetails = data;
      if (!this.studentDetails.success) {
        this.messageClass = 'alert alert-danger'; // Set an error class
        this.message = this.studentDetails.message; // Set an error message
        } else {
        this.messageClass = 'alert alert-success'; // Set a success class
        this.message = this.studentDetails.message; // Set a success message

        this.router.navigate(['/home']);
      }
    })
  }

  onFileSelected(event){
    this.selectedFile = <File>event.target.files[0];


  }
  onUpload(){

    let formData = new FormData();
    for (var i = 0; i < this.selectedFile.length; i++) {
        formData.append("file", this.selectedFile[i], this.selectedFile[i].name);
    }

  }


  ngOnInit() {
  }

}

    student.service.ts
    import { Injectable } from '@angular/core';
import 'rxjs/add/operator/map';
import { HttpClient, HttpResponse } from '@angular/common/http';


@Injectable({
  providedIn: 'root'
})
export class StudentService {
  domain = "http://localhost:3000/";

  constructor(
    private http: HttpClient
  ) { }



getDetails(user){
  return this.http.post(this.domain + 'authentication/register', user).map(res =>res)
}

}

    enter code here
   my backend code
router.post('/register', upload.single('file'),[
    check('fullName').isAlphanumeric().isLength({mn:1}).withMessage('FullName is required'),
    check('email').isEmail().isLength({min:1}).withMessage('Email is required'),
    check('fatherName').isAlpha().withMessage('Father name is required'),
    check('motherName').isAlpha().withMessage('Mother name is required'),
    check('mobilenumber').isNumeric().isLength({min:10}).withMessage('Enter a valid Mobile Number')
],  
  (req,res)=>{


    const errors=validationResult(req);
     if(!errors.isEmpty()){
         return res.status(422).json({errors:errors.array()})
     }


     let student=new Student({
         email:req.body.email,
         fatherName:req.body.fatherName,
         motherName:req.body.motherName,
         mobilenumber:req.body.mobilenumber,
         fullName : req.body.fullName, 
         file: req.file
     });


      student.save((err)=>{
         if(err){
              res.json({success:false, message:'Unable to save the user Error:', err})
         }else{
             const output =`
             <p>You have a new Student Registered</p>
             <h3>Student Details</h3>
             <ul>
             <li>FullName: ${req.body.fullName}</li>
             <li>Email: ${req.body.email}</li>
             <li>Phone: ${req.body.mobilenumber}</li>
             <li>FatherName:${req.body.fatherName}</li>
             <li>MotherName: ${req.body.motherName}</li>
             </ul>
              `;




            res.json({success:true, message:'Student Registered '})

          }
     })

0 个答案:

没有答案