Я изучаю около nodejs и Angular. Я создал веб-приложение для реализации изображений, используя NodeJs и Angular. Тем не менее, у меня были проблемы при отправке изображения на сервер. Это мой код:
<form action="/api/upload" method="post" enctype="multipart/form-data">
<div class="form-group">
<label for="example-input-file" (change)="fileChange($event)" type="file" ng-model="up.file"
class="custom-file-input" id="inputGroupFile01" aria-describedby="inputGroupFileAddon01"> </label>
<input type="file" name="file" class="form-control-file border">
</div>
<div>
<button type="submit" class="btn btn-primary" (click)="upload()" id="btnUpload">Upload</button>
</div>
</form>
form.component.ts
uploadedFiles: Array < File > ;
fileChange(element) {
this.uploadedFiles = element.target.files;
}
upload() {
let formData = new FormData();
for (var i = 0; i < this.uploadedFiles.length; i++) {
formData.append("uploads[]", this.uploadedFiles[i], this.uploadedFiles[i].name);
}
this.http.post('/api/upload', formData)
.subscribe((response) => {
console.log('response received is ', response);
})
app. js
var express = require('express');
var app = express();
var multer = require('multer')
const multipart = require('connect-multiparty');
const multipartMiddleware = multipart({ uploadDir: './upload' });
app.get('/api/upload', (req, res) => {
res.json({
'message': 'hello'
});
});
let uploadFile = multer({storage: diskStorage}).single("file");
app.post('/api/upload', (req, res) => {
uploadFile(req, res, (error) => {
if (error) {
return res.send(`Error when trying to upload: ${error}`);
}
res.sendFile(path.join(`${__dirname}/uploads/${req.file.filename}`));
});
});
Большое спасибо !!!