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

文件上载控制响应窗体

  •  0
  • Tachyon  · 技术社区  · 6 年前

    发行

    我现在有一个表单,有一堆字段,其中一个是文件上传字段。它们都是一个整体的一部分 FormGroup 在我的构造函数中声明的。现在我可以使用 this.control.value 除了我的文件控制。当我尝试访问 value 我得到的只是 C:/fakepath/image.png .

    有没有办法访问实际的文件数据,以便我可以上传到我的API?


    我的 FormControl

    /**
     * Category of the product
     */
    public category = new FormControl('', [
      Validators.required
    ]);
    
    /**
     * Name of the product
     */
    public name = new FormControl('', [
      Validators.required,
      Validators.minLength(3)
    ]);
    
    /**
     * Description of the product
     */
    public description = new FormControl('', [
      Validators.required
    ]);
    
    /**
     * Price of the product
     */
    public price = new FormControl('', [
      Validators.required
    ]);
    
    /**
     * Image of the product
     */
    public image = new FormControl('', [
      Validators.required
    ]);
    

    我的页面/组件构造函数:

    constructor(private api: ApiService,
      private formBuilder: FormBuilder) {
    
        this.productForm = formBuilder.group({
          category: this.category,
          name: this.name,
          description: this.description,
          price: this.price,
          image: this.image
        });
    }
    

    我当前如何尝试访问该文件

    public async createProduct(): Promise<any> {
      console.log(this.image.value);
    }
    
    0 回复  |  直到 6 年前
        1
  •  3
  •   Kunal Mukherjee    6 年前

    <div class="form-group">
        <label for="file">Choose File</label>
        <input type="file"
               id="file"
               (change)="handleFileInput($event.target.files)">
    </div>
    

    第2步:在TypeScript中上载处理(在组件文件中)

    为所选文件定义默认变量。

    fileToUpload: File = null;
    

    handleFileInput(files: FileList) {
        this.fileToUpload = files.item(0);
    }
    

    第三步:文件上传服务

    postFile(fileToUpload: File): Observable<boolean> {
        const endpoint = 'your-destination-url';
        const formData: FormData = new FormData();
        // Append image file to formdata as a seperate property
        formData.append('fileKey', fileToUpload, fileToUpload.name);
    
        // Append reactive form data too in a seperate property
        formData.append('productForm', JSON.stringify(this.productForm, null, 4));
        return this.httpClient
          .post(endpoint, formData, { headers: yourHeadersConfig })
          .map(() => { return true; })
          .catch((e) => this.handleError(e));
    }
    
        2
  •  0
  •   Vadi    6 年前

    有没有办法访问实际的文件数据,以便我可以上传到我的API?

    // template
    <input
     type="file" (change)="onFileChanged($event)"
    >
    
    // component
    onFileChanged(event) {
      // this.image will be updated each time the file
      // in input will be changed
      this.image = event.target.files[0];
      console.log(this.image);
    }
    
    
    createProduct(): Promise<Product> {
      console.log(this.image);
      const formData = new FormData();
      formData.append(
        'image',
        this.image
      );
    
      // add other fields to formData:
      formData.append("name", this.productForm.controls['name'].value);
    
      formData.append("description", this.productForm.controls['description'].value);
    
      const url = 'urlToApi';
    
      return this.http.post(url, formData)
        .toPromise()
        .then(response => {
          return response;
        })
        .catch(err => console.log(err));
    }