代码之家  ›  专栏  ›  技术社区  ›  Rupesh

将图像从角度上传到nodejs时出错

  •  -1
  • Rupesh  · 技术社区  · 6 年前

    我的 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的图片地址

    正如埃里克建议的那样-

    我的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);
          });
     });
    

    它给予 result 作为 undefined

    1 回复  |  直到 6 年前
        1
  •  0
  •   Eric Yang    6 年前

    这基本上是图像数据的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
    });