сохранить файл видео-большого двоичного объекта с клиента на Flask сервер - PullRequest
0 голосов
/ 06 августа 2020

Я записываю видео + звук в моем js клиенте с помощью MediaStreamRecorder. js. Я получаю пакеты данных с ondataavailable. Я вижу в браузере, что большой двоичный объект имеет разумный размер в зависимости от длины записи. Я конвертирую blob / data в файл. Я прикрепляю файл к объекту formdata. Я отправляю его с помощью fetch в мое серверное приложение python / flask. Я получаю файл, но его размер 0.

{% extends "layout.html" %}
 {% block content %}

          <article class="media content-section">


            <div class="media-body">


            {#  <form    method="POST" action="">
               {{form.hidden_tag()}}
                  <fieldset class="form-group">
                      <legend class="borer-bottom mb-4"> New Video </legend>

                       {#<div class="form-group">
                          {{form.content.label(class="form-control-label")}}
                          {% if form.content.errors %}
                              {{ form.content(class="form-control form-control-lg is-invalid") }}
                              <div class="invalid-feedback">
                                  {% for error in form.content.errors %}
                                      <span>{{error}}</span>
                                  {% endfor %}
                              </div>
                          {% else %}
                             {{form.content(class="form-control form-control-lg")}}
                          {% endif %}
                      </div>
                  </fieldset>
                   <div class="form-group">
                          {{form.submit(class="btn btn-outline-info")}}

                   </div>
               </form> #}


              <button id="btn-start-recording">Start Recording</button>
              <button id="btn-stop-recording" disabled="disabled">Stop Recording</button>



              {#<h1> Streaming </h1>
              <img src="{{ url_for('users.stream') }}" />#}

              <!--
                  2. Include a video element that will display the current video stream
                  and as well to show the recorded video at the end.
               -->
              <hr>
              <video id="my-preview" controls autoplay></video>
              <video id="my-saver"></video>
              <!-- 3. Include the RecordRTC library and the latest adapter -->
              <script src="https://cdn.webrtc-experiment.com/MediaStreamRecorder.js"> </script>

                  <script>

                      MediaStreamRecorder.prototype.getBlob = function() {
                              return this.blob;
                          };
                      var video = document.getElementById('my-preview');
                      var mediaRecorder;
                      var blobURL;
                      let recordedChunks = [];
                      var blob;
                      function setSrcObject(stream, element) {
                          if ('srcObject' in element) {
                              element.srcObject = stream;
                          } else if ('mozSrcObject' in element) {
                              element.mozSrcObject = stream;
                          } else {
                              element.srcObject = stream;
                          }
                      }
                      var global_stream;

                        //Util function to stop the camera
                        function stopBothVideoAndAudio(stream) {
                                          stream.getTracks().forEach(function(track) {
                                              if (track.readyState == 'live') {
                                                  track.stop();
                                              }
                                          });
                                      }

                       // When the user clicks on start video recording
                      document.getElementById('btn-start-recording').addEventListener("click", function(){

                          // Disable start recording button
                          this.disabled = true;
                          document.getElementById('btn-stop-recording').disabled = false;
                          var mediaConstraints = {
                              audio: true,
                              video: true
                          };



                          navigator.getUserMedia(mediaConstraints, onMediaSuccess, onMediaError);



                          function onMediaSuccess(stream) {

                              mediaRecorder = new MediaStreamRecorder(stream);

                              setSrcObject(stream, video);
                              global_stream = stream

                              video.muted = true;
                              mediaRecorder.mimeType = 'video/webm';

                              mediaRecorder.ondataavailable = function (e) {
                                 
                                    recordedChunks.push(e.data);
                                
                              };

                              mediaRecorder.start(300000);

                          }

                          function onMediaError(e) {
                              console.error('media error', e);
                          }
                      }, false);


                         // When the user clicks on Stop video recording
                      document.getElementById('btn-stop-recording').addEventListener("click", function(){
                           console.info('im in stop recording clicked!');

                          this.disabled = true;

                          document.getElementById('btn-start-recording').disabled = false;
                                console.info(' open start button...');
                                console.info(' stop recording...');

                                stopBothVideoAndAudio(global_stream);

                                //02082020
                                mediaRecorder.stop();
                               // let blob = mediaRecorder.requestData();

                                  blob = new Blob(recordedChunks, {
                                      type: 'video/webm'
                                    });
                                //let blob = mediaRecorder.getBlob();
                                console.info(' stop preview...');

                                 video.srcObject=mediaRecorder.stream;
                                 video.play();
                                 video.muted = false;


                                  var fileName = 'my_very_own_vid' + '.mp4';


                                  var file = new File([blob], fileName, {
                                      type: 'video/webm'
                                  });

                                  //new 02082020
                                  //objectURL = window.URL.createObjectURL(blob) //URL.createObjectURL(blob)

                                 // var binaryData = [];
                                  //binaryData.push(blob);
                                  //objectURL = window.URL.createObjectURL(new Blob(binaryData, {type: "application/zip"}))


                                const url = "{{ url_for("users.user_question", filename=file) }}";
                                  const formData = new FormData();
                                  formData.append("video", file);
                                  fetch(url, {
                                    method: 'POST',
                                    body: formData,
                                  }).then(res => {
                                    if(res.ok) alert('OK!');
                                  }).catch(err => {
                                    alert(err);
                                  });

                                console.info('stream stpped');
                              // Enable record button again !
                      }, false);

                  </script>
            </div>

        </article>

{% endblock content%}

def user_question():
    question_num = '1'

    if request.method == "POST":
        saveVideo()

    #return render_template('user_question_form_02.html', question_num=question_num)  # , form=form)
    return render_template('user_question_form_04.html', question_num=question_num)#, form=form)
    #return render_template('user_question.html', question_num=question_num)  # , form=form)

def saveVideo():

        files = request.files
        print('files is')
        print(files)
        #if "video" in files:
        for file in request.files["video"]:
            print(str(file))
            with open(os.path.join("c:/test/", "video_from_client.webm"), 'wb') as out:
                out.write(file)
                return Response()

        print('finished daving file')
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...