在Angular 5中上传文件时保存FormData

8

我正在尝试使用Angular 5中的FormData保存文件。我可以获取单个文件,但不知道如何获取所有已上传的文件。我有三个图像文件和输入字段,并尝试搜索示例。但是只能得到用于多个文件上传的示例。我想要从此表单中上传每一个文件。

以下是我的代码:

import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { Location } from '@angular/common';
import { ActivatedRoute } from '@angular/router';
import { Category } from '../../../shared/services/categories/category';
import { CategoriesService } from '../../../shared/services/categories/categories.service';

@Component({
  selector: 'app-add-category',
  templateUrl: './add-category.component.html',
  styleUrls: ['./add-category.component.scss'],
  encapsulation: ViewEncapsulation.None
})
export class AddCategoryComponent implements OnInit {
  
  category: Category = new Category();
  fileToUpload: File = null;
  
  constructor(
    private categoriesService: CategoriesService,
    private route: ActivatedRoute,
    private location: Location  
  ) { }

  ngOnInit() {
  }

  goBack(): void {
    this.location.back();
  }

  handleFileInput(files: FileList) {
    console.log(files);
  }

  addCategory() {
    console.log(this.category);
    this.categoriesService.createCategory(this.category).subscribe(() => this.goBack());
  }

}
          <h3 class="box-title">Category</h3>

        <form role="form" (ngSubmit)="addCategory()" #categoryForm="ngForm">

              <div class="box-body">

                <div class="row">
                  <div class="col-lg-6">
                  <label for="Category Name">Name</label>
                  <input type="text" class="form-control" [(ngModel)]="category.category_name" name="category_name" id="category_name" placeholder="Enter Category Name" required="">
                </div>

                <div class="col-lg-6">
                  <label for="Category Path">Path</label>
                  <input type="text" class="form-control" [(ngModel)]="category.category_path" name="category_path" id="category_path" required="">
                </div>
              </div>
            </div>
            <br/>

            <div class="form-group">
                  <label for="Category Description">Description</label>
                  <textarea rows="3" [(ngModel)]="category.category_description" name="category_description" id="category_description" class="form-control" required=""></textarea>
            </div>
                
            <div class="col-lg-12 text-center">
                <input type="file" [(ngModel)]="category.category_banner" (change)="handleFileInput($event.target.files)" class="custom-file-input" name="category_banner" id="category_banner">
                <label class="custom-file-label" for="customFile">Banner</label>
            </div>
            <br/>

            <div class="form-group">
              <label for="Category Banner Code">Banner Code</label>
              <textarea rows="3" [(ngModel)]="category.category_banner_code" name="category_banner_code" id="category_banner_code" class="form-control" required=""></textarea>
            </div>
            
            <br/>
            
            <div class="col-lg-12">
                <input type="file" [(ngModel)]="category.category_image" (change)="handleFileInput($event.target.files)" class="custom-file-input" name="category_image" id="category_image">
                <label class="custom-file-label" for="customFile">Image</label>
            </div>
        
            <br/>

            <div class="col-lg-12">
                <input type="file" [(ngModel)]="category.category_icon" (change)="handleFileInput($event.target.files)" class="custom-file-input" name="category_icon" id="category_icon">
                <label class="custom-file-label" for="customFile">Icon</label>
            </div>

              <div class="form-group">
              <label for="Category Meta Title">Meta Title</label>
              <input type="text" [(ngModel)]="category.category_meta_title" class="form-control" name="category_meta_title" id="category_meta_title" placeholder="Enter Meta Title" required="">
            </div>

            <div class="form-group">
              <label for="Category Meta Description">Meta Description</label>
              <input type="text" [(ngModel)]="category.category_meta_decription" class="form-control" id="category_meta_description" name="category_meta_description" placeholder="Enter Meta Description" required="">
            </div>

            <div class="form-group">
              <label for="Category Meta Keyword">Meta Keyword</label>
              <input type="text" [(ngModel)]="category.category_meta_keyword" class="form-control" id="category_meta_keyword" name="category_meta_keyword" placeholder="Enter Meta Keyword" required="">
            </div>

            <div class="form-group">
             
              <div class="row">
                 <div class="col">Featured :</div>
                <div class="col">
                <label class="radio-inline" for="Category Featured">
                  <input type="radio" [(ngModel)]="category.category_featured" name="category_featured" id="category_featured" value="1" required="">Yes
                </label>
              </div>

              <div class="col">
                <label class="radio-inline" for="Category Featured">
                  <input type="radio" [(ngModel)]="category.category_featured" name="category_featured" id="category_featured" value="0" required="">No
                </label>
            </div>
            </div>
            </div>
              
            <input type="hidden" [(ngModel)]="category.category_status" name="category_status" id="category_status" value="1">

              <div class="box-footer col-md-12">
                <button type="submit" class="btn btn-primary">Submit</button>
              </div>
            </form>

6个回答

13

最近我遇到了类似的问题。在Angular代码中将头部内容类型设置为空可以解决这个问题。 以下是Angular5和Spring Boot后端的代码片段。

let headers = new HttpHeaders();
//this is the important step. You need to set content type as null
headers.set('Content-Type', null);
headers.set('Accept', "multipart/form-data");
let params = new HttpParams();
const formData: FormData = new FormData();
for (let i = 0; i < this.filesList.length; i++) {
  formData.append('fileArray', this.filesList[i], this.filesList[i].name);
} 
formData.append('param1', this.param1);
formData.append('param2', this.param2);
this.http.post(this.ROOT_URL + this.SERVICE_ENDPOINT, formData, { params, headers }).subscribe((res) => {
    console.log(res);
});



In the spring boot backend, you need to have the controller as - 

@RequestMapping(value = "/uploadAndSendEmail", method = RequestMethod.POST, consumes= "multipart/form-data")    
public ResponseEntity<String> uploadAndSendEmail(@RequestParam("fileArray") MultipartFile[] fileArray, 
        @RequestParam(value = "param1", required = false) String param1,
        @RequestParam(value = "param2", required = false) String param2) {
        //do your logic
        }

6

这是我如何处理单个文件输入中的多个文件的方法。 我的组件收集表单数据并生成一个不包含文件的Data对象。然后它使用该Data对象和文件调用此服务方法,该方法将以multipart post方式发送数据和文件。

  save(data: Data, filesForUpload: File[]): Observable<Data> {
    const formData = new FormData();

    // add the files
    if (filesForUpload && filesForUpload.length) {
      filesForUpload.forEach(file => formData.append('files', file));
    }

    // add the data object
    formData.append('data', new Blob([JSON.stringify(data)], {type: 'application/json'}));

    return this.http.post<Data>(this.apiUrl, formData);
  }

因此,要处理两个文件输入,您可以这样做:
 save(data: Data, filesA: File[], filesB: File[]): Observable<Data> {
    const formData = new FormData();

    // add the files
    if (filesA && filesA.length) {
      filesA.forEach(file => formData.append('filesA', file));
    }

    if (filesB && filesB.length) {
      filesB.forEach(file => formData.append('filesB', file));
    }

    // add the data object
    formData.append('data', new Blob([JSON.stringify(data)], {type: 'application/json'}));

    return this.http.post<Data>(this.apiUrl, formData);
  }

您需要将上传的文件分为三个部分:每个文件集合一个部分,数据对象一个部分。

1
我不想从单个文件输入处理多个文件。 我对filesA和filesB的示例不清楚。我尝试了这个:code' handleFileInput(files: FileList) { this.fileToUpload = files.item(0); }'code我有三个图像上传按钮,我想将它们与formData一起在post中发送。 - Kamlesh Katpara
单文件上传与多文件上传相同,仍在数组中,但数组中只有一个项目。或者,您可以通过 files.item(0); 传递一个项目。在示例中,我假设有两个输入,并传入了两个文件数组。如果有三个输入,则会传递三个数组(或三个单独的项目)。我将它们分别发送到POST中的原因是,这样您就可以在服务器端知道哪个文件来自于哪个输入。 - GreyBeardedGeek

4

我尝试了以下操作,结果符合预期:

handleCategoryBanner(files: FileList) {
    this.category.category_banner = '/categories/download/' + files[0].name;
    this.formData.append('category_banner', files[0], files[0].name);
    this.categoryContainersService.uploadFile(this.formData).subscribe(filename => console.log(files[0].name));
  }
<div class="col-lg-12 text-center">
        <input type="file" (change)="handleCategoryBanner($event.target.files)" class="custom-file-input" id="category_banner" accept=".jpeg,.png,.jpg">
        <input type="hidden" name="category_banner" [(ngModel)]="category.category_banner" />
        <label class="custom-file-label" for="customFile">Banner</label>
    </div>


1

在您的输入标签上只需添加'multiple'属性,现在通过选择2个或更多文件进行浏览,您将获得一个对象,应该迭代它以提取其中的图像。像这样-->

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

它不是来自于同一个上传字段。 - Kamlesh Katpara

0

我也遇到了同样的问题,以下代码对我有用:

postFile(apiPath: string, data:any){
    this.http.post<any>(apiPath, data).subscribe(
      (res) => console.log(res),
      (err) => console.log(err)
    );

0

尝试这段代码:

handleFileInput(files){
     for (let j = 0; j < files.length; j++) {
      let data = new FormData();
      let fileItem = files[j]._file;
      console.log(fileItem.name);
      data.append('file', fileItem);
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接