Загрузить захваченное видео на сервер с помощью FormData в ioni c 4 - PullRequest
6 голосов
/ 09 июля 2020

Я успешно записал видео с моего устройства android, но не могу загрузить его на сервер с помощью formData и не могу показать видео в html. ниже мой код:

video.ts

captureVideo() {
let options: CaptureVideoOptions = {
  limit: 1,
  // duration: 30,
};
this.mediaCapture.captureVideo(options).then(
  (res: MediaFile[]) => {
    let capturedFile = res[0];
    this.readVideoFile(capturedFile);
  },
  (err: CaptureError) => console.error(err)
);
}

readVideoFile(file: any) {
//console.log('inside readVideo', file);

var movVideo = {
  uri: file['localURL'].split('/'),
  type: 'video/mp4',
  name: file.name,
  size: file.size,
};
var imageBlob = new Blob([file], movVideo);
const formData = new FormData();
formData.append('file', imageBlob, file.name);
//console.log('FORM DATA 515 ---->', formData.getAll('data'));
this.upload.captureFileUpload(formData).subscribe(
  (res) => {
    // Store the token value in local storage for future use.
    //console.log('------------captureImageFileUpload resp--------', res);
  },
  (err) => {
    //console.log('------------captureImageFileUpload err--------', err);
  }
);
}

видео. html

<ion-icon
    name="videocam"
    class="send"
    slot="end"
    (click)="captureVideo()"
    *ngIf="!isDesktop"
  ></ion-icon>


  <video controls class="chat-video">
   <source src="{{attachment_file_path}}?name={{attachValue.fileName}}" type="{{attachValue.mimeType}}"/>
    Your browser does not support HTML video.
  </video>

Любая помощь очень ценится

1 Ответ

3 голосов
/ 15 июля 2020

FormData просто предоставит вам объект с именем файла, URL-адресом и .... после отправки formData будет выглядеть так:

enter image description here

Code of FormData:

  const form = document.getElementById('formElem');
  form.onsubmit = (e) => {
    e.preventDefault();


    let formData = new FormData();
    formData.append('section', 'general');
    formData.append('action', 'previewImg');
    // Attach file
    formData.append('image', document.getElementsByTagName('input')[1].files[0]);
    
    const uploadFile = async () => {
      const result = await fetch('./images/',
        {
          method: 'POST',
          body: JSON.stringify(formData),
          headers: {
            'Content-Type': 'multipart/form-data'
          }

        });
      console.log(result)

    }
    uploadFile();
  };

once you have data of the file you need to have the bank-end end-point to receive and upload(save) it to somewhere, depends on your backend if you use Node, python, PHP, you need to look for the similar library of file uploading

Let's try the below example,

isUploading: boolean = false;
uploadPercent: number = 0;
videoFileUpload: FileTransferObject;
loader;

uploadVideo() {
        var url = baseUrl +  "/video/upload";
        
        var filename = this.selectedVideo.substr(this.selectedVideo.lastIndexOf('/') + 1);
          
        var options: FileUploadOptions = {
          fileName: filename,
          fileKey: "video",
          mimeType: "video/mp4"
        }
    
        this.videoFileUpload = this.transfer.create();
    
        this.isUploading = true;
    
        this.videoFileUpload.upload(this.selectedVideo, url, options)
          .then((data)=>{
            this.isUploading = false;
            this.uploadPercent = 0;
            return JSON.parse(data.response);
          })
          .then((data) => {        
            this.uploadedVideo = data.url;
            this.presentAlert("Success", "Video upload was successful.");
          })
          .catch((err)=>{
            this.isUploading = false;
            this.uploadPercent = 0;
            this.presentAlert("Error", "Error uploading video.");
          });
    
        this.videoFileUpload.onProgress((data) => {
          this.uploadPercent = Math.round((data.loaded/data.total) * 100);
        });
    
      }

uploadVideo() : Okay, we have selected a video, we have a server ready to accept our upload, so what’s keeping us from uploading? Nothing!!! Here we make use of the FileTransfer plugin to upload our video to the server. This part is divided into majorly two segments: One is responsible for uploading the file to the server. The other is responsible to keeping track of upload progress.

resources: https://forum.ionicframework.com/t/how-can-i-upload-image-from-camera-files-like-multipart-form-data/130663

  1. Учебное пособие

  2. тот же вопрос

  3. тот же вопрос с FormData Загрузка файла FormData

...