угловая отправка файлов на сервер - PullRequest
0 голосов
/ 12 ноября 2019

Я пытаюсь отправить файлы двух типов в целом на сервер images и zip Я уже установил

"@ionic-native/file": "^5.16.0",
"@ionic-native/file-transfer": "^5.16.0",
"cordova-plugin-file": "^6.0.2",
"cordova-plugin-file-transfer": "^1.7.1",

Я также импортировал файлы классов в свой компонент, например:

import {FileTransfer, FileUploadOptions, FileTransferObject} из '@ ionic-native / file-Transfer / ngx';import {File} из '@ ionic-native / file';

конструктор (// и т. д. частная передача: FileTransfer, приватный файл: File) {}

, и я получаю этопредупреждение:

one

Код

Вот моя форма на виду

<form class="ion-padding" [formGroup]="distributorForm" (ngSubmit)="approveDistributor()">
    <ion-row class="ion-padding">
        <ion-col size="12">
            <ion-input type="file" formControlName="coDoc" placeholder="Company documents"></ion-input>
            <small>1- Only <kbd>Zip</kbd> files are allowed. <br> 2- Maximum size: <kbd>10 MB</kbd></small>
        </ion-col>

        <ion-col size="12">
            <ion-button class="ion-margin-top" type="submit" expand="full" color="success" [disabled]="!distributorForm.valid">SEND</ion-button>
        </ion-col>
    </ion-row>
</form>

Вот мой текущий компонентфункция without files (это отправка данных в сервис.

approveDistributor() {
    const distributorForm = this.distributorForm.value;
    // tslint:disable-next-line: max-line-length
    this.verifyService.distributorForm(distributorForm.coDoc).subscribe(
      data => {
        this.alertService.presentToast('Sent successfully.');
      },
      error => {
        this.alertService.presentToast(error['message']);
      },
      () => {

        this.Mainstorage.ready().then(() => {

          this.Mainstorage.get('token').then(
            data => {
              this.alertService.presentToast('Your data is in process after approve you\'ll be able to work with software.');
            },
            error => {
              console.log(error);
            }
          );

        });

      }
    );
  }

Вот моя сервисная функция (это отправка данных на сервер)

distributorForm(
    coDoc: String
    ) {
    const headers = new HttpHeaders({
      Authorization : this.token.token_type + " " + this.token.access_token,
      Accept: 'application/json, text/plain',
      'Content-Type': 'application/json'
    });
    return this.http.post(this.env.companyDocs,
      {
        coDoc
      }, { headers }
    );
  }

Вопросы

  1. Должен ли я беспокоиться о предупреждении, которое я получу для FileTransfer? Если да, то как его решить?
  2. Как получить правильный путь к моим файлам для отправки их на сервер?

Обновление

Я изменил свою функцию для использования formData, например:

    const distributorForm = this.distributorForm.value; //my original line

    //added lines
    const formData: FormData = new FormData();
    formData.append('coDoc', distributorForm);
    console.log(formData); // this returns empty array under formData in console.

    // tslint:disable-next-line: max-line-length
    this.verifyService.distributorForm(formData).subscribe(
...
);

даже при formData Я не могу отправить файл на сервер.

1 Ответ

0 голосов
/ 13 ноября 2019
 saveComp() {


            var value: File = file;//get file from input 

            this.customService.saveFile(value)
                .subscribe((data: any) => {
                    // do some stuff

                }, (error: any) => console.log(error))


            return;
           }




saveFile(file: File): any {
        const formData: FormData = new FormData();
       var url="your url";
       //example url= "http://localhost:9090/"+ 'api/CrmLead/CreateFollowUpByExcel';
        formData.append('FollowUpFile', file, file.name);
        return this._http.post(url, formData, this.requestOptions)
            .catch(this.errorHandler);
    }
  requestOptions = {
        headers: new HttpHeaders({

            'Authorization': 'Bearer ' + token,

        })
    };

В ApiController C #

                var httpRequest = _httpContextAccessor.HttpContext.Request;
                var postedFile = httpRequest.Form.Files["FollowUpFile"];

                string path = null;
                if (postedFile != null)
                {
                // do some stuff with file                     

                }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...