我正在尝试使用节点js中的multer上传角度为5的图像。但它没有上传。
我使用formData获取角度5中的文件详细信息并将数据发送到后端。但它没有在这里上传。
这是我现在拥有的代码
event-create.component.html看起来像这样
function PHPFMG( formID ){
var myprice = pricecalc();
var redirect = 'https://www.paypal.me/tim/' + myprice;
}
event-create.component.ts看起来像这样
<div class="container col-md-10">
<h1 class="page-header">Create Event</h1>
<form [formGroup] = "form" (ngSubmit)="onEventSubmit()">
<fieldset>
<div class="form-group">
<label for="eventname">Event Name</label>
<div class='input-group date col-sm-6'>
<input type="text" class="form-control" autocomplete="off" placeholder="Event Name" formControlName="eventname">
</div>
</div>
<div class="form-group">
<label for="eventimage">Event Image</label>
<div class="input-group">
<span class="input-group-btn">
<span class="btn btn-default btn-file">
Browse… <input type="file" id="eventimage" name="eventimage" formControlName="eventimage" (change)="fileChangeEvent($event)" >
</span>
</span>
<input type="text" class="form-control" readonly>
</div>
<img id='img-upload'/>
</div>
<input type="submit" class="btn btn-primary" value="Submit">
</fieldset>
</form>
</div>
event.service.ts看起来像这样
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { FormControlName } from '@angular/forms/src/directives/reactive_directives/form_control_name';
import { EventService } from '../event.service';
import { Response } from '@angular/http';
@Component({
selector: 'app-event-create',
templateUrl: './event-create.component.html',
styleUrls: ['./event-create.component.css']
})
export class EventCreateComponent implements OnInit {
private file_form;
form : FormGroup;
message;
messageClass;
processing = false;
filesToUpload: Array<File> = [];
constructor(
private formBuilder : FormBuilder,
private eventService : EventService,
) { this.createEventForm(); }
createEventForm() {
this.form = this.formBuilder.group({
eventname: ['', Validators.required],
eventimage: [''],
})
}
ngOnInit() {
}
onEventSubmit() {
const event = {
eventname : this.form.value.eventname,
eventimage : this.file_form,
}
this.eventService.addNewEvent(event).subscribe( data => {
if( !data.success ) {
this.messageClass = 'alert alert-danger';
}
else {
this.messageClass = 'alert alert-success';
}
});
}
fileChangeEvent(event) {
let files = event.target.files;
if(files.length > 0) {
let file = files[0];
let formData = new FormData();
formData.append('eventimage', file, file.name);
this.file_form = formData;
}
}
}
my express.js看起来像这样
import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs';
import { HttpClientModule } from '@angular/common/http';
import { HttpClient } from "@angular/common/http";
import 'rxjs/add/operator/map';
@Injectable()
export class EventService {
domain = 'http://localhost:8080';
headers = new Headers({ 'Content-Type': 'application/json' });
constructor(
private http: Http,
) { }
addNewEvent(event) {
return this.http.post(this.domain + '/event', {headers: this.headers}, event).map(res => res.json());
}
}
event.router.js看起来像这样
/* ===================
Import Node Modules
=================== */
const express = require('express');
const app = express();
const router = express.Router();
const mongoose = require('mongoose');
const config = require('./database');
const path = require('path');
const appRoot = require('app-root-path') ;
const event = require('./routes/event.router');
const bodyParser = require('body-parser');
const multer = require('multer');
const cors = require('cors');
const port = process.env.PORT || 8080; // Allows heroku to set port
mongoose.Promise = global.Promise;
process.env.NODE_ENV = 'production';
// Database Connection
mongoose.connect(config.uri, {
useMongoClient: true,
}, (err) => {
// Check if database was able to connect
if (err) {
console.log('Could NOT connect to database: ', err); // Return error message
} else {
console.log('Connected to ' + config.db); // Return success message
}
});
app.use(cors());
//app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(express.static(path.join(appRoot.path, 'dist')));
app.use('/event', event);
// Serve only the static files form the dist directory
app.get('*', (req, res) => {
res.sendFile(path.join(appRoot.path, 'dist/index.html'));
});
// Start Server: Listen on port 8080
app.listen(port, () => {
console.log('Listening on port ' + port + ' in ' + process.env.NODE_ENV + ' mode');
});
有人可以告诉我这里做错了什么。任何帮助和建议都会非常明显。
以下是chrome dev工具的截图。
我不知道为什么thetimage会显示为空白对象。
答案 0 :(得分:0)
addNewEvent(event) {
return this.http.post(this.domain + '/event', {headers: this.headers}, event).map(res => res.json());
}
如果我没弄错,看起来你只是发送标题 - 认为你的参数顺序错误。来自文档:
post(url: string, body: any, options?: RequestOptionsArgs): Observable<Response>
所以你的标题选项会出现在正文之前。试试这个:
return this.http.post(this.domain + '/event', event, {headers: this.headers}).map(res => res.json());