我将从Angular 2发送formdata到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代码中,我没有收到任何文件和发布数据。
答案 0 :(得分:0)
您必须将mime类型放在表单上,就像在JQuery Ajax中一样,具有属性
mimeType: "multipart/form-data"