开发者

What's the right way to upload multiple files in angular?

开发者 https://www.devze.com 2022-12-07 20:58 出处:网络
I\'m trying to upload a series of files to an endpoint. Using a http client in my case insomnia the process concludes satisfactorily

I'm trying to upload a series of files to an endpoint. Using a http client in my case insomnia the process concludes satisfactorily

Http client options

What's the right way to upload multiple files in angular?

Headers

What's the right way to upload multiple files in angular?

Payload

What's the right way to upload multiple files in angular?

With the http client I can confirm that process ends successfully

When I try the same in angular I get 400 Bad request error

@Injectable({
  providedIn: 'root',
})
export class ResourcesService {
  private readonly ENDPOINT = '/backend/api/content';

  constructor(private readonly httpClient: HttpClient) {}

  upload(files: FileList) {
    const formData = new FormData();
    formData.append('files', files[0], files[0].name);

    // Array.from(files).forEach((file) =>
    //   formData.append('files', file, file.name)
    // );

    // for (let i = 0; i < files.length; i++) {
    //   formData.append('files', files[i], files[i].name);
    // }

    return this.httpClient.post<ResourceModel[]>(
      `${this.ENDPOINT}/upload`,
      formData,
      {
        headers: new HttpH开发者_JAVA百科eaders({
          'Content-Type': 'multipart/form-data',
        }),
      }
    );
  }


I managed to solve the problem by removing the header. The other modification was to iterate each file in the list of files

The final result is the following

@Injectable({
  providedIn: 'root',
})
export class ResourcesService {
  private readonly ENDPOINT = '/backend/api/content';

  constructor(private readonly httpClient: HttpClient) {}

  upload(files: FileList) {
    const formData = new FormData();

    Array.from(files).forEach((file) =>
      formData.append('files', file, file.name)
    );

    return this.httpClient.post<ResourceModel[]>(
      `${this.ENDPOINT}/upload`,
      formData
    );
  }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号