【问题标题】:Not able to send formData to the server无法将 formData 发送到服务器
【发布时间】:2019-12-28 19:55:27
【问题描述】:
  • 我正在使用 Angular 框架,
  • 我试图通过 FormData 向服务器发送数据
  • 我正在分享我的代码

component.ts

const ProposalData: FormData = new FormData();
ProposalData.append('customerId', this.customerId);
ProposalData.append('file', this.file);
const token  = localStorage.getItem('currentUser');
this.rest.newProposals(ProposalData , token).subscribe(
        result => { console.log(result) } 
                                        );

service.ts

newProposals(value , token) {
   let headers = new HttpHeaders();
   headers = headers.append('Content-Type', 'application/json; charset=utf-8');
   headers = headers.append('Authorization', token);
   return this.http.post<any>(this.addProposals , value , {headers});
  }

问题是

一旦我尝试通过 Post 方法将我的 formData 发送到服务器,我的数据在服务器上没有到达并且我的 FormData 在服务器上是空的 .

注意:当我 console.log formData 时,数据被控制台是正确的。但它不会以某种方式发送到服务器

【问题讨论】:

    标签: angular angular6 angular5 angular-httpclient


    【解决方案1】:

    你可以在component.ts中这样尝试

     uploadPhoto() {
    
       let userid = "43345;
      this.LoaderService.display(true);
      var nativeElement: HTMLInputElement = this.fileInput.nativeElement;
      var file = nativeElement.files[0];
      nativeElement.value = '';
      this.sampleService.ImageUpload(userid, file)
        .subscribe(photo => {
          this.LoaderService.display(false);
         ,
          err => {
            this.LoaderService.display(false);
    
          });
    

    }

    在您的 HTML 文件中的 .HMTL 文件中这样做

      <input class="hidden" type="file" (change)="readURL($event);" name="Uploadfile" 
       id="file" style="width: 100%;cursor: pointer;" #fileInput>
    

    在服务文件中如下所示

        ImageUpload(id, file) {
        var formData = new FormData();
        formData.append('file', file);
        return this.Http.post(this.url+ 'ImageUpload' + '/' + id, formData);
      }
    

    在WEB API中这样做

    [HttpPost("ImageUpload/{Id}")]
    public async Task<IActionResult> plantFileUpload(string id, [FromForm(Name = "file")] IFormFile file)
    {
    
    }
    

    这应该可行

    【讨论】:

      【解决方案2】:

      将常量类型从headers = headers.append('Content-Type', 'application/json; charset=utf-8'); 更改为

      headers = headers.append('Content-Type', 'application/x-www-form-urlencoded'); in service file 
      

      更正Service.ts文件

      newProposals(value , token) {
         let headers = new HttpHeaders();
         headers = headers.append('Content-Type', 'application/x-www-form-urlencoded');
         headers = headers.append('Authorization', token);
         return this.http.post<any>(this.addProposals , value , {headers});
        }
      

      【讨论】:

        【解决方案3】:

        在您的 .HTML 文件中

        <input type='file' id="upload_file" name="images" (change)="onChangeEvent($event)">
        

        在您的 component.ts 文件中

        onChangeEvent(event) {
            this.selectedFileName = [];
            let fileList: FileList = event.target.files;
            let i;
            for (i = 0; i < fileList.length; i++) {
                let label = fileList[i].name;
                this.uploadFileName.set(i, label);
                this.selectedFileName.push(label);
            }
            this.uploadImages();
          }
        
          uploadImages() {
            let fileList = this.elem.nativeElement.querySelector('#upload_file').files;
        
            if (fileList.length === 0) {
                swal.fire(
                    'File upload Error.',
                    'Please select Document.',
                    'error');
            } else {
                let i;
                let formData: FormData = new FormData();
                formData.append('length', fileList.length);
        
                for (i = 0; i < fileList.length; i++) {
                    let file: File = fileList[i];
                    let fname = file.name;
                    let fsize = file.size;
                    let ftype = file.type;
        
           if (ftype === 'application/pdf' || ftype === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' || ftype === 'application/msword' || ftype === 'image/jpeg' || ftype === 'image/jpg' || ftype === 'image/png') {
                        this.layoutService.showLoading();
                        formData.append('user_profile_picture', file, file.name);
                    } else {
                        swal.fire(
                            'Unsupported Document',
                            'Only PDF, PNG, JPG and DOCX Type Allow.',
                            'error');
                        this.layoutService.hideLoading();
                        return false;
                    }
                }
        
                this.profileService.uploadProfilePic(formData).subscribe(response => {
                    this.layoutService.hideLoading();
                    this.getProfilePic();
                }, (err) => {
                    this.layoutService.hideLoading();
                });
             }
           }
        

        服务文件

         public uploadProfilePic(formdata: any) {
            let headers = new HttpHeaders();
            return this._http.post(environment.apiUrl + 'user- 
         profile/upload_user_profile_picture', formdata, {headers: headers});
         }  
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-03-22
          相关资源
          最近更新 更多