【问题标题】:error in uploading the image from angular to nodejs将图像从角度上传到nodejs时出错
【发布时间】:2019-01-10 15:51:17
【问题描述】:

我的Html file 是 -

<form method="post" [formGroup]="orderForm" enctype="multipart/form-data" (ngSubmit)="OnSubmit(orderForm.value)" >
      <div class="form-group">
        <label for="image">Select Branch Image</label>
        <input type="file" formControlName="branchImg" (change)="onFileChange($event)" class="form-control-file" id="image">
      </div>
</form>

而我的.ts file 是-

public orderForm: FormGroup;

onFileChange(event) {
    const reader = new FileReader();

    if (event.target.files && event.target.files.length) {
      const [file] = event.target.files;
      reader.readAsDataURL(file);

      reader.onload = () => {
        this.orderForm.patchValue({
          branchImg: reader.result
        });               
      };
    }
  }

ngOnInit() {
    this.orderForm = this.formBuilder.group({
      branchImg: [null, Validators.required]
    });
  }

然后提交表单。

我应该在cloudinary获取图片地址并上传该地址

但是当我在我的 nodejs 应用程序中安慰身体时

它给出了这样的东西-

branchImg: 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAgAAAQABAAD/7QCEUGhvdG9zaG9wIDMuMAA4QklNBAQAAAAAAGccAigAYkZCTUQwMTAwMGE4MjBkMDAwMD and so on.

我不认为这是图像地址。谁能告诉我这是什么?以及如何获取我将上传到 cloudinary 的图片地址

正如 Eric 建议的那样 -

我的 app.js 代码是

router.post('/branch',(req,res) =>{
    const body = req.body;
      const base64Data = body.branchImg.replace(/^data:image\/png;base64,/, "");
      console.log(base64Data);
      fs.writeFile("out.jpg", base64Data, 'base64', function(err,result) {
        console.log(result);
      });
 });

它给出resultundefined

【问题讨论】:

  • “base64”之后的位是编码为base64的图像。如果用户上传了图片,就没有可以使用的地址,需要图片数据

标签: html node.js angular


【解决方案1】:

这基本上是图像数据的base64编码。得到之后你需要做的就是将它写入一个文件,然后将它上传到 cloudinary

//this will write the base64 data as a jpg file to your local disk
require("fs").writeFile("out.jpg", base64Data, 'base64', function(err) {
    //after you write it to disk, use the callback space here to upload said file
    //to your cloudinary endpoint
});

【讨论】:

  • 当我在做 console.log(result) 时,它会给出未定义的输出
  • 抱歉,如果你想在回调中看到需要函数(错误,结果)而不仅仅是函数(错误)的东西。话虽如此,您已经有了文件名 out.jpg,所以只要没有错误,您就可以正确保存它。然后你将 out.jpg 发送到你的最终目的地
  • 是的,我使用result 作为回调,但它提供了undefined
  • 对不起,该函数不返回结果,只是成功或错误。所以如果你的错误是空的,你就可以走了。您实际上不需要任何结果。如前所述,您已经预先知道文件名。
  • 答案不变。我的答案没有结果
猜你喜欢
  • 2022-06-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-18
  • 1970-01-01
  • 1970-01-01
  • 2020-04-29
  • 2018-12-26
相关资源
最近更新 更多