Angular 6 - Загрузка файлов - PullRequest
       7

Angular 6 - Загрузка файлов

0 голосов
/ 10 сентября 2018

Я пытаюсь отправить файлы (видео и миниатюры) и объект на сервер, но у меня проблема из-за ожидаемой структуры бэкэнда. Когда я делаю это из почтальона, вот как это выглядит и работает:

{'name': ['Blabla'], 'user': ['8c3a636c-9d08-453d-9e59-7a0ec93200c4'], 'file': [<InMemoryUploadedFile: SampleVideo_1280x720_1mb.mp4 (video/mp4)>]}>

У меня проблемы с передачей файла, как этот, не знаю, как это сделать. Я пытался сделать это так:

videoFile: File[] = [];
thumbnailFile: File[] = [];
files: File[] = [];

readVideoUrl(event:any) {
      this.videoFile = [];
        const eventObj: MSInputMethodContext = <MSInputMethodContext> event;
        const target: HTMLInputElement = <HTMLInputElement> eventObj.target;
        const files: FileList = target.files;
        if (files) {
            this.videoFile.push(files[0]);
            this.videoModel.name = files[0].name;
        }


        if (event.target.files && event.target.files[0]) {
            var reader = new FileReader();

            reader.onload = (event: ProgressEvent) => {
                this.videoUrl = (<FileReader>event.target).result;
            }

            reader.readAsDataURL(event.target.files[0]);
        }
    }

readThumbUrl(event:any) {
    this.thumbnailFile = [];
    const eventObj: MSInputMethodContext = <MSInputMethodContext> event;
    const target: HTMLInputElement = <HTMLInputElement> eventObj.target;
    const files: FileList = target.files;
    if (files) {
        this.thumbnailFile.push(files[0]);
    }

    if (event.target.files && event.target.files[0]) {
        var reader = new FileReader();

        reader.onload = (event: ProgressEvent) => {
            this.thumbUrl = (<FileReader>event.target).result;
        }

        reader.readAsDataURL(event.target.files[0]);
    }
}

Я передаю модель и файлы:

this.campaignService.createVideo(this.videoModel, this.files)
                  .subscribe(
                      (response: any) => {
                      },
                      (error) => {
                          console.log(error);
                      }
                  );

И вот в чем проблема, как я могу создать структуру сверху с данными формы, я делал это так:

postMultipart(url: string, data: any, files: File[]) {
        const formData: FormData = new FormData();

        // I understand this stringify is part of the issue, 
        // just put the code as it is at the moment.
        formData.append('data', JSON.stringify(data));
        for (const file of files) {
            formData.append(file.name, file);
        }
        const result = this.http.post(url, formData)
            .pipe(map((response: Response) => {

                    return response;
                    // }
                }),
                catchError(response => this.handleError(response))
            );
        return result;
    }

Но все это проходит как строка, и серверная часть этого не ожидает. Как я могу получить это (это просто видео, миниатюра это изображение):

{'file': [<InMemoryUploadedFile: SampleVideo_1280x720_1mb.mp4 (video/mp4)>]}>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...