File Angular2通过HTTP向API发送文件
我一直很难通过我正在构建的Angular2/NodeJS应用程序将文件发送到后端API。我尝试了很多不同的东西和建议,但似乎没有任何效果,我也不知道为什么。首先,这是我的代码 我的视图代码File Angular2通过HTTP向API发送文件,file,http,post,angular,upload,File,Http,Post,Angular,Upload,我一直很难通过我正在构建的Angular2/NodeJS应用程序将文件发送到后端API。我尝试了很多不同的东西和建议,但似乎没有任何效果,我也不知道为什么。首先,这是我的代码 我的视图代码 <input type='file' (change)='fileChangeEvents($event)' placeholder='Upload file...' /> <button (click)='upload()'>Upload Files</button>
<input type='file' (change)='fileChangeEvents($event)' placeholder='Upload file...' />
<button (click)='upload()'>Upload Files</button>
我也尝试过使用XHR请求的解决方案(不使用Angular2的http对象),但这也不起作用
当我使用POSTMAN发送文件时,我在我的NodeJS路由中捕获请求,并且该文件位于req.body属性中,这非常奇怪。这会提示我Angular2功能不正确。有人能看到这里出了什么问题吗?检查一下,或者我已经尝试过这个解决方案,但仍然一无所获。req对象中的NodeJS函数中没有接收到任何文件。req.body中没有req.uploadFile或任何内容。当我在formData变量后添加断点时,似乎也没有在其中设置任何内容?请检查,或者我已经尝试了此解决方案,但仍然没有设置任何内容。req对象中的NodeJS函数中没有接收到任何文件。req.body中没有req.uploadFile或任何内容。当我在formData变量后添加断点时,似乎也没有任何设置?
fileChangeEvents(fileInput: any) {
this._filesToUpload = <Array<File>> fileInput.target.files;
}
upload() {
this._filesService.sendFile(routes.api.files, [], this._filesToUpload)
.subscribe((result) => {
console.log(result);
}, (error) => {
console.log(error);
});
}
sendFile(url: String, vars: Array<String>, files: File[]):Observable<any> {
let headers = HttpHelper.createAuthorizationHeader(true);
let options = new RequestOptions({ headers: headers });
let files = files;
const formData = new FormData();
for(var i = 0; i < files.length; i++){
formData.append(files[i].name, files[i]);
}
return this._http
.post(url, formData)
.map((res) => {
return res.json();
});
}
router.post('/upload', function(req, res, next) {
filesRoutesControllerObjectInstance.upload(req, res, next);
});