How to upload RecordRTC blob file to Rails papercl

2019-02-11 03:12发布

On the client side, the user uses RecordRTC to record a short video. When the user presses upload, I will get the video's blob data using recorder.getBlob(), and upload it to my server (using Rails and paperclip to handle file upload).

At first, I wanted to change the <input type='file'> field value to the blob data. It turns out that for security in browsers, I cannot change it using javascript.

Then, I tried to use AJAX:

$("#ajax-submit").on("click", function() {
    var data = new FormData();

    data.append("record[video]", recorder.getBlob(), (new Date()).getTime() + ".webm");

    var oReq = new XMLHttpRequest();
    oReq.open("POST", "/records/");
    oReq.send(data);
    oReq.onload = function(oEvent) {
        if (oReq.status == 200) {
            console.log("Uploaded");
        } else {
            console.log("Error " + oReq.status + " occurred uploading your file.");
        }
    };
});

However, it does not work. On log file, I will get the following, which cannot be handled:

Processing by RecordsController#create as */*
Parameters: {
  "video"=>"data:video/webm;base64,GkXfo0AgQoaBAUL3gQFC8o..."
}

If I submit normally using form, I will have parameters look like this:

Processing by RecordsController#create as HTML
Parameters: {
    "video"=>#<ActionDispatch::Http::UploadedFile:0x3b476e0 @original_filename="testing.mp4", @content_type="video/mp4", @headers="Content-Disposition: form-data; name=\"record[video]\"; filename=\"testing.mp4\"\r\nContent-Type: video/mp4\r\n", @tempfile=#<File:a_path>>
}

How could I solve the problem?

Many thanks.

2条回答
Melony?
2楼-- · 2019-02-11 03:42

I handled kind of same problem in one of my project. The situation was the API has to convert a blob data to image file that was being sent by a mobile device. I am assuming the action to be upload in your controller file.

def upload
  #extract the video data from params
  video = params[:video]

  # define the save path for the video. I am using public directory for the moment. 
  save_path = Rails.root.join("public/videos/#{video.original_filename}")

  # Open and write the file to file system.
  File.open(save_path, 'wb') do |f|
    f.write params[:video].read
  end

  render :nothing => true
end
查看更多
倾城 Initia
3楼-- · 2019-02-11 04:03

In the end, the cause of problem is that the blob file returned from recorder.getBlob() is not an actual blob. Refer to the answer from muaz-khan.

I added the following lines in RecordRTC to get the real blob and do the same AJAX submitted. Everything work now.

         getBlob: function () {
             return blobURL2;
         },
+        getRealBlob: function() {
+            return blobURL;
+        }, 
查看更多
登录 后发表回答