我是自学 Angular ,在尝试将图像和文本发布到服务器时感到很困难。当使用 postman 测试时,后端按预期工作,但在使用 Angular 时失败。这是我使用的代码:
上传.component.html
<form [formGroup]="uploadForm" (ngSubmit)="onSubmit()">
<div class="form-group">
<label for="description">Trip Name</label>
<input type="text" name="description" class="form-control" formControlName="text" placeholder="description">
</div>
<div class="form-group">
<label for="image">Cover Image</label>
<input type="file" name="image" class="form-control-file" id="image">
</div>
<input type='submit' value="Submit" class="btn btn-primary" />
</form>
上传.component.ts
private preSubmit(): any {
let input = new FormData();
input.append('description', this.uploadForm.get('description').value);
input.append('image', this.uploadForm.get('image').value);
return input;
}
onSubmit() {
const newImage = this.preSubmit();
this.http.post('apiUrl', newImage)
}
NodeJS
router.post('/', multer().single('image'), async (req, res) => {
const upload = {
imgID: uuidv4(),
description: req.body.description,
image: req.file.originalname,
};
postparams = { Key: upload.imgID, Body: req.file.buffer };
await s3Bucket.putObject(postparams, (err, data) => {
if (err) {
console.log('Error uploading Image: ', err);
} else {
console.log('Image uploaded: ', upload.imgID);
}
});
knex('image')
.insert(image).then(images => {
res.json(images)
});
});
感谢您的帮助!
最佳答案
我不是专家,但试试这个。
uploadForm: FormGroup;
private preSubmit(): any {
let input = new FormData();
input.append('description', this.uploadForm.value.description);
input.append('image', this.uploadForm.value.image);
return input;
}
或者这个
private preSubmit(): any {
return this.uploadForm = new FormGroup ({
description: new FormControl(),
image: new FormControl() })
}
关于node.js - 使用 Angular、express 和 multer 发布图像和文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50289948/