首页 > 解决方案 > 使用角度上传带有base64的图像时,假路径存储在mongodb中

问题描述

        Angular:
        I'm trying to upload an image through angular using base64 format but in MongoDB, it stores the fake path i.e 'c://fakepath/filename.jpg' instead of storing  base64 string
        
             onSubmit(): any {
            //     this.url=this.newuserForm.value;
        
            // this.newuserForm.value.file =this.url
            // let d=sessionStorage.getItem('image');
            // this.newuserForm.value.files=d;
        
            // console.log("before fetch"+this.newuserForm.value.file);
        
        
            this.crudService.AddUser(this.newuserForm.value)
              .subscribe((d) => {
                console.log('Data added successfully!');
                console.log(d);
                //  this.url=d.files;
                console.log("new file" + d.file);
        
        
                this.ngZone.run(() => this.router.navigateByUrl('/useraction'))
              }, (err) => {
                console.log(err);
              });
          }
        
             // file upload
          onSelectFile(event: any) {
            if (event.target.files && event.target.files[0]) {
              var reader = new FileReader();
        
              reader.readAsDataURL(event.target.files[0]); // read file as data url
        
        
              reader.onload = (event: any) => { // called once readAsDataURL is completed
                this.url = event.target.result;
                //store image from base 64 format 
                console.log("my ts file url is " + this.url);
                sessionStorage.setItem('image', this.url)
                this.newuserForm.value.file = this.url;
        
              }
            }
          }
        
        
        Html :

这是使用我正在尝试上传文件的 Html 文件

            label class="hoverable" for="fileInput">
                    <img  name="image" [src]="url ? url : 'https://www.w3schools.com/howto/img_avatar.png'" width="50px" height="50px"> 
                    <div class="hover-text">Change Image
                      <!-- <img class="camimg" src="assets/cameraicon.jpg" /> -->
                
                    </div>
                    <div class="background"></div>
                  </label>
                  <br/>
                <input id="fileInput" type='file' formControlName="file"  (change)="onSelectFile($event)">
        

CrudeService.ts 这是一个 crud 服务文件,我正在尝试调用后端 API 和后端模型我已将文件类型作为字符串 // 添加用户 AddUser(data: Users): Observable { let API_URL = ${this.REST_API}/add-user; 返回 this.httpClient.post(API_URL, data) .pipe( catchError(this.handleError) ) }

标签: htmlangulartypescript

解决方案


推荐阅读