我可以用邮递员上传图像,但角度不适合我。解决方案,请
错误:无法在nodejs中读取undefined的原始名称,但带有 邮递员的工作!
//后端
var express = require("express")
var router = express.Router();
var userModel = require("../models/userModel")
const jwt= require("jsonwebtoken")
const bcrypt=require("bcrypt")
var app=express()
var io = require('socket.io-client')('http://localhost:3000/alll')
var socket = require("socket.io");
var fs=require("fs")
var multer=require("multer")
const upload = multer({dest: __dirname + '/upload/images'});
router.post('/uploads', upload.single('image'), function (req, res) {
var file = __dirname + '/upload' + req.file.originalname;
fs.readFile(req.file.path, function (err, data) {
fs.writeFile(file, data, function (err) {
if (err) {
console.error(err);
var response = {
message: 'Sorry, file couldn\'t be uploaded.',
filename: req.file.originalname
};
} else {
response = {
message: 'File uploaded successfully',
filename: req.file.originalname
};
res.json(response);
}
})
})
})
router.post("/add",function (req, res) {
user = new userModel({firstName: req.body.firstName,
lastName: req.body.lastName ,
email:req.body.email ,
password:req.body.password,
adresse:req.body.adresse,
verif:'1',role :'user',
annonces:req.body.annonces,
pdf: req.body.pdf
})
user.save(function(err) {
if (err) {
res.send({"state": "not ok", "msg": "err:" + err})
} else {
res.send({"state": " ok", "msg": "ajout"})
}
})
})
// model : pdf as String
// ts
import {ChangeDetectorRef, Component, OnInit, TemplateRef} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {Router} from '@angular/router';
import {UserService} from '../services/user.service';
import {ConnecterComponent} from '../connecter/connecter.component';
import {BsModalRef, BsModalService} from 'ngx-bootstrap/modal';
import { FileUploader } from 'ng2-file-upload';
@Component({
selector: 'app-singin',
templateUrl: './singin.component.html',
styleUrls: ['./singin.component.css']
})
export class SinginComponent implements OnInit {
registrationForm: FormGroup;
submit = false;
fileSelected: File
emailuser: String;
modalRef: BsModalRef;
selectedFiles: FileList;
currentFileUpload: File;
imgURL: any;
imgname;
errorValidImage = '';
URL ='http://localhost:3000/users/uploads';
constructor(private router: Router, private userService: UserService, private formbuilder: FormBuilder , private cd : ChangeDetectorRef, private modalService: BsModalService ) { }
ngOnInit() {
this.registrationForm = this.formbuilder.group({
email: [ '', [ Validators.required, Validators.email]],
password: ['', [ Validators.required, Validators.minLength(8)]],
firstName:['',[ Validators.required]],
lastName: ['', Validators.required],
adresse:['', Validators.required],
pdf:[''],
});
}
get f() {
return this.registrationForm.controls;
}
OnSubmit(){
this.submit = true;
if (this.registrationForm.invalid) {
return;
}
console.log(this.registrationForm.value)
localStorage.setItem('var', '1');
this.userService.updateimagee(this.currentFileUpload).subscribe(res=>{
this.imgname=JSON.parse(JSON.stringify(res['filename']));
this.userService.register(this.registrationForm.value.firstName,this.registrationForm.value.lastName,this.registrationForm.value.email,this.registrationForm.value.password,this.registrationForm.value.adresse,this.registrationForm.value.pdf=this.imgname).subscribe( res => {
console.log(res['status'])
});
this.userService.login(this.registrationForm.value.email,this.registrationForm.value.password).subscribe(res=>{
localStorage.setItem('var', '1')
localStorage.setItem('emailuser',JSON.parse(JSON.stringify(res['data'])).email)
this.emailuser=localStorage.getItem('emailuser')
console.log(res['status'])
console.log(JSON.parse(JSON.stringify(res['data'])).token);
// console.log(JSON.parse(JSON.stringify(res['data'])).id);
var iduser = parseInt(JSON.parse(JSON.stringify(res['data'])).id);
sessionStorage.setItem('id', JSON.parse(JSON.stringify(res['data'])).id);
this.router.navigate(['']);
})
})
}
selectFile(event) {
this.selectedFiles =event.target.files;
this.currentFileUpload = this.selectedFiles.item(0);
console.log(this.currentFileUpload);
const reader = new FileReader();
reader.onload = (event) => {
this.imgURL = reader.result;
};
console.log(this.imgURL);
console.log(reader);
} }
// html
<div class="container">
<form method="POST" class="appointment-form" id="appointment-form" [formGroup]="registrationForm" (ngSubmit)="OnSubmit()" enctype="multipart/form-data">
<h2>education appointment form</h2>
<div class="form-group-1">
<div [class]="form-control" >
<input type="text" class="form-control" formControlName="firstName" placeholder="First Name" [ngClass]="{'is-invalid':submit && f.firstName.errors} " />
<span class="focus-input100" data-placeholder=""></span>
<div *ngIf="submit && f.firstName.errors" class="invalid-feedback">
<div *ngIf="f.firstName.errors.required">firstName is required </div>
</div>
</div>
<div [class]="form-control" >
<input type="text" formControlName="lastName" placeholder="Last Name" class="form-control" [ngClass]="{'is-invalid':submit && f.lastName.errors}" />
<div *ngIf="submit && f.lastName.errors" class="invalid-feedback">
<div *ngIf="f.lastName.errors.required">LastName is required </div>
</div>
</div>
<div [class]="form-control" >
<input type="email" formControlName="email" placeholder="Email" class="form-control" [ngClass]="{'is-invalid':submit && f.email.errors}" />
<div *ngIf="submit && f.email.errors" class="invalid-feedback">
<div *ngIf="f.email.errors.required">Email is required </div>
</div>
</div>
<div [class]="form-control" >
<input type="password" formControlName="password" placeholder="Password" class="form-control" [ngClass]="{'is-invalid':submit && f.password.errors}" />
<div *ngIf="submit && f.password.errors" class="invalid-feedback">
<div *ngIf="f.password.errors.required">Password is required </div>
<div *ngIf="f.password.errors.minlength">Au moins 8 caracteres </div>
</div>
</div>
<div [class]="form-control" >
<input type="text" formControlName="adresse" placeholder="Adresse local" class="form-control" [ngClass]="{'is-invalid':submit && f.adresse.errors}" />
<div *ngIf="submit && f.adresse.errors" class="invalid-feedback">
<div *ngIf="f.adresse.errors.required">Adresse is required </div>
</div>
</div>
<div class="custom-file">
<input type="file" class="custom-file-input" id="customFile" (change)="selectFile($event)" formControlName="pdf" [ngClass]="{'is-invalid':submit && f.pdf.errors}" />
<label class="custom-file-label">Photo de profil</label>
</div>
<div class="form-submit">
<input type="submit" name="submit" id="submit" class="submit" value="Submit" />
</div>
</div>
</form>
</div>
</div>
但是控制台说后端有错误:
TypeError:无法读取未定义的属性“ originalname” 在C:\ Users \ hazem \ Desktop \ pfe \ router \ user.js:114:47
答案 0 :(得分:-1)
似乎您没有使用过ng2-file-upload库。尝试这样的事情。
import { Component, OnInit } from '@angular/core';
import { FileUploader, FileSelectDirective } from 'ng2-file-upload/ng2-file-upload';
const UploadURL = 'http://localhost:3000/api/upload';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
title = 'Upload a File';
public uploader: FileUploader = new FileUploader({url: URL, itemAlias: 'image'});
ngOnInit() {
this.uploader.onAfterAddingFile = (file) => { file.withCredentials = false; };
this.uploader.onCompleteItem = (item: any, response: any, status: any, headers: any) => {
console.log('FileUpload:uploaded:', item, status, response);
alert('File uploaded successfully');
};
}
}
行
public uploader: FileUploader = new FileUploader({url: URL, itemAlias: 'image'});
很重要。确保在混合中间件中使用相同的名称(“ 图片”), 像这样
upload.single('image')