node.js - 使用 Angular、express 和 multer 发布图像和文本

标签 node.js angular express form-data

我是自学 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/

相关文章:

node.js - 使用 Express Web 框架的阿拉伯语 URL 路由?

javascript - 在 node.js 中将数组传递给 jade 模板时出现问题

JavaScript 正则表达式 : successive matches

javascript - 在 Node.js 中将文件转换为 UTF-8 文件

angular - 无法在拦截器使用的服务内实例化循环依赖关系

javascript - Node.js- "npm install express"错误 :0906D06C :PEM routines : PEM_read_bio npm

node.js - APN Node : Error when loading PEM file

angular - 在MatSnackBar中使用 "snackBar.openFromComponent()"方法时,如何放置 Action 按钮?

angular - @ngrx/reducer : createReducer(), 和 on() 不是类型安全的?

node.js - 在 react 中从数据库获取数据的正确方法是什么?