我目前正在Angular2中开发一个应用程序,它由一个与API通信的NodeJS实例包装。我目前正在实现一些文件上传功能,并且无法获取捕获NodeJS层中的API文件上载请求的功能,以显示它正在捕获文件。 这是我的代码: 我的文件上传Angular2服务: } 捕获api请求的NodeJS路由并将其转发给NodeJS中的控制器函数: 应该捕获请求并将文件发送到API的函数: 当我调试请求时,当我在NodeJS'ouoload'路由和控制器中调试'req'对象时,请求中没有文件。正如您所看到的,我正在尝试使用FormData Angular2功能发送它们。谁能看到我在这里做错了什么。 import { Component } from "@angular/core";
import { routes } from "../../../routes";
import { FilesService } from "../../../services/files.service";
@Component({
selector : 'file-upload',
moduleId : module.id,
templateUrl : '/app/views/files/file-upload.html',
})
export class FileUploaderDirective {
private _filesToUpload: Array<File> = [];
constructor(
private _filesService: FilesService
) {
}
fileChangeEvents(fileInput: any) {
this._filesToUpload = <Array<File>> fileInput.target.files;
}
upload() {
this._filesService.sendFile(routes.api.files, [], this._filesToUpload)
.then((result) => {
console.log(result);
}, (error) => {
console.log(error);
});
}
}
import { Injectable } from "@angular/core";
import { Observable } from "rxjs";
@Injectable()
export class FilesService {
constructor() {
}
sendFile(url: String, vars: Array<String>, files: File[]): Promise<any> {
return new Promise((resolve, reject) => {
let formData: FormData = new FormData(),
xhr: XMLHttpRequest = new XMLHttpRequest();
for (let i = 0; i < files.length; i++) {
formData.append("uploads[]", files[i], files[i].name);
}
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
resolve(JSON.parse(xhr.response));
} else {
reject(xhr.response);
}
}
};
xhr.open('POST', url, true);
xhr.send(formData);
});
}
router.post('/upload', function(req, res, next) {
filesRoutesControllerObjectInstance.upload(req, res, next);
});
var ApiBase_RequestLayer = require('../ApiBase_RequestLayer'),
Config = require(global.appRoot + '/Config'),
util = require('util');
function Files() {
Files.super_.call(this);
this.requestBaseUrl = Config.brain.url + '/upload';
}
Files.prototype.upload = function(req, res) {
if(req) {
}
};
util.inherits(Files, ApiBase_RequestLayer);
module.exports = Files;