繁体   English   中英

如何在 Laravel 中检索 FormData

[英]How to retrieve FormData in Laravel

我正在将表单数据从 Angular 2 发送到 Laravel API,以保存来自 RecordRTC js 的录制语音。 在控制台上检查文件名、文件类型和 blob 文件。 它正在显示。 但无法在 Laravel 后端代码上检索。

 public uploadToServer() {
    let blob  = this.recordRTC instanceof Blob ? this.recordRTC : this.recordRTC.blob;
    let fileType = blob.type.split('/')[0] || 'audio';
    let fileName = (Math.random() * 1000).toString().replace('.', '');
    if (fileType === 'audio') {
      fileName += '.' + (!!navigator.mozGetUserMedia ? 'ogg' : 'wav');
    } else {
      fileName += '.webm';
    }
    // create FormData
    var formData: FormData = new FormData();
    console.log(fileName);
    console.log(blob);
    console.log(fileType);
    formData.append(fileType + '-filename', fileName);
    formData.append(fileType + '-blob', blob);
    console.log(formData);
    this.recordingService.saveRecording(formData).subscribe(
      data => this.saveRecordingSuccess(data),
      error => this.saveRecordingFail(error)
    );
  }

Laravel 代码:-

 public function saveRecording(Request $request)
  {
    $fileName = '';
    $tempName = '';
    $file_idx = '';

    if (!empty($_FILES['audio-blob'])) {
        $file_idx = 'audio-blob';
        $fileName = $_POST['audio-filename'];
        $tempName = $_FILES[$file_idx]['tmp_name'];
    }
    if (empty($fileName) || empty($tempName)) {
        if(empty($tempName)) {
            echo 'Invalid temp_name: '.$tempName;
            return;
        }
        echo 'Invalid file name: '.$fileName;
        return;
    }
    $filePath = public_path('voiceRecording/' . $fileName);

    // make sure that one can upload only allowed audio/video files
    $allowed = array(
        'webm',
        'wav'
    );
    $extension = pathinfo($filePath, PATHINFO_EXTENSION);
    if (!$extension || empty($extension) || !in_array($extension, $allowed)) {
        echo 'Invalid file extension: '.$extension;
        return;
    }
    if (!move_uploaded_file($tempName, $filePath)) {
      // error code
        return;
    }
}

在 Laravel 代码中,我没有收到任何文件和发布数据。

你必须在你的表单上加上 mime 类型,就像在 JQuery Ajax 中一样,有属性

mimeType: "multipart/form-data"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM