Jag försökte göra samma sak och här är min lösning (osäker på om detta är det bästa sättet att göra det),
server js:
var formidable = require('formidable');
var fs = require('fs');
app.post('/upload', function(req, res){
var form = new formidable.IncomingForm();
form.multiples = false;
form.uploadDir = path.join(__dirname, '/public/uploads');
form.on('file', function(field, file) {
fs.rename(file.path, path.join(form.uploadDir, file.name));
});
form.on('error', function(err) {
console.log('An error has occured: \n' + err);
});
form.on('end', function() {
res.end('success');
});
form.parse(req);
});
app.component:
import { Component, OnInit, NgZone } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: 'js/app/app.component.html'
})
export class AppComponent {
filesToUpload: Array<File>;
constructor() {
this.filesToUpload = [];
}
upload() {
this.makeFileRequest("http://localhost:3000/upload", [], this.filesToUpload).then((result) => {
console.log(result);
}, (error) => {
console.error(error);
});
}
fileChangeEvent(fileInput: any){
this.filesToUpload = <Array<File>> fileInput.target.files;
}
makeFileRequest(url: string, params: Array<string>, files: Array<File>) {
return new Promise((resolve, reject) => {
var formData: any = new FormData();
var xhr = new XMLHttpRequest();
for(var i = 0; i < files.length; i++) {
formData.append("uploads[]", files[i], files[i].name);
}
xhr.open("POST", url, true);
xhr.send(formData);
});
}
}
}
Notera:Detta använder formidabel och inte multer