Save FormData with File Upload in Angular 5

前端 未结 5 876
鱼传尺愫
鱼传尺愫 2021-01-01 00:49

I am trying to save files along with FormData in Angular 5. I can get the single file, but have no idea how to get all the files uploaded. I have three image files and input

5条回答
  •  温柔的废话
    2021-01-01 01:20

    Here's how I handle multiple files from a single file input. My component gathers the form data, and produces a Data object, which does not contain the files. It then calls this service method with the Data object and the files, which sends the data and the files in a multipart post.

      save(data: Data, filesForUpload: File[]): Observable {
        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(this.apiUrl, formData);
      }
    

    So, to handle two file inputs, you could do this:

     save(data: Data, filesA: File[], filesB: File[]): Observable {
        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(this.apiUrl, formData);
      }
    

    Which would give you three parts in your multipart post, one for each set of files, and one for the data object.

提交回复
热议问题