Python 至 Laravel 上传 mp4 文件

Python to Laravel Upload mp4 File

我正在用 raspberry pi 构建家庭监控并在 python 中编码,我正试图通过 [=33] 将一些 mp4 文件发送到 Laravel 服务器=] 编码,我试图在 python 上进行 base64 编码并在 php 中解码,但是当我接收并保存文件时,文件似乎已损坏。所以我想知道我该怎么做,或者有更好的方法吗?

我想知道是否可能是编码文件丢失了一部分,因为我正在比较我发送的字符串与相同的字符串,但将其取回并且显示为 false 是相等的。

如果你想在 python 上查看我的代码,我就是这样做的也是。

def record_video(self):
    print('Recording')
    url = 'http://127.0.0.1:8080/stream/video.mjpeg'
    local_filename = url.split('/')[-1]
    filename = time.strftime("%Y%m%d-%H%M%S")+'.mp4'
    save_path = '/home/pi/Downloads/tesis/video'
    completed_video= os.path.join(save_path, filename)

    ##using ffmpeg to record the video
    pro = subprocess.Popen('ffmpeg -i '+url+' '+completed_video+' -y', stdout=subprocess.PIPE, 
                   shell=True, preexec_fn=os.setsid)
    time.sleep(10)
    ##stop the recording
    os.killpg(os.getpgid(pro.pid), signal.SIGTERM)

    print('Sending')

    ##reading the file wi rb(read byte)
    with open(completed_video,'rb') as f:

        ##encode the video
        encode_video = base64.b64encode(f.read())

        ##put it on the json file
        json = {'ip_address': '10.10.10.110',
                'date': time.strftime('%Y-%m-%d %H:%M:%S'),
                'video': encode_video}

        ##make post request
        r = self.api.post(json,'createvideo')
        a = r.json()
        print('send')
        print(a)
        path = pathlib.Path(completed_video) ##Im deleting the file after is send
        path.unlink()

然后对于 post 请求,我这样做:

def post(self,json,api):
    return request(self.url+api, json, headers={'Accept': 'application/json'})

在我的 php 解码 mp4 文件中,我这样做:

    $this->validate(request(),[
        'ip_address' => 'required',
        'date' => 'required',
        'video' => 'required'
    ]);

    $device = Device::where('ip_address',request('ip_address'))->first();
    $video_encode = request('video');

    $decoded = base64_decode($video_encode);

    $path = public_path().'/video/'.$device->id.'/';

    $date = new \DateTime('now');
    $stringdate = date_format($date, 'Y-m-d H:i:s');
    $file_name = $path.str_random(8).'.mp4';

    $file = fopen($file_name,'wb');
    fwrite($file,$decoded);
    fclose($file);

    $video = Video::create([
        'date' => request('date'),
        'device_id' => $device->id,
        'video' => $file_name
    ]);

    return response()->json([ 'data' => $video]);

我设法创建了一个文件,但它似乎损坏了。

我会参考 如何使用请求 post 发送文件: file_ = {'file': ('video.mp4', open('video.mp4', 'rb'))} r = requests.post(upload_url, files=file_)

然后我会查看 the laravel documentation 以了解如何管理上传文件的存储: $path = request()->file->store('images');

您应该能够进行文件验证,并且无需对数据进行碱基编码。希望将 open() 传递给 file_requests 处理文件。