我一直在尝试修改请求以使用新移动的文件切换上传的文件(我必须首先将其移动到带有音频扩展名的临时文件,以便我可以使用 getID3 ),所以我可以使用CustomAudioValidator
验证它(使用 getID3 ,默认的mimetypeguesser并不是很好,因为有时它会返回application / octet-stream)。
问题是使用替换不起作用,所以我深入了解并发现它是混合的
$request->files and $request->all()
所以我试过
$request->files->replace
但是$request
仍然没有改变,并且继续使用不存在且.tmp
扩展的第一个上传文件(我将其移动到临时目录,其中包含任何音频扩展名)例如mp3
);
有没有办法明确地改变这个要求,或者我有什么方法可以绕过这个?
public function store(Request $request)
{
if ($request->hasFile('music')){
$music = $request->file('music');
$originalName = $music->getClientOriginalName();
$localtempfilename = $music->move(public_path('uploads\tmp'), $originalName);
$requestReplace = array('size' => intval($localtempfilename->getSize()/1000),
'user' => Auth::user()->id,
);
$request->replace($requestReplace);
$request->files->replace(array('music' => new UploadedFile($localtempfilename->getPathname(), $originalName) )); // $request is modified with new UploadedFile with correct paths
$this->validate($request, Music::getRules()); //$request still uses old $music to validate and gives an error about file path inexistant since I moved it
}
}
class CustomAudioValidator {
public function validateType($attribute, $value, $parameters, $validator)
{
if (!($value instanceof UploadedFile)) return false;
if ($fp_remote = fopen($value->getPathname(), 'rb')) {
if ($fp_local = fopen($value->getPathname(), 'wb')) {
while ($buffer = fread($fp_remote, 8192)) {
fwrite($fp_local, $buffer);
}
fclose($fp_local);
// Initialize getID3 engine
$getID3 = new getID3;
$fileInfo = $getID3->analyze($value->getPathname());
}
fclose($fp_remote);
}
else throw(New FileNotFoundException($value->getPathname() . ' doesn\'t exist '));
if (in_array( $fileInfo['mime_type'],
['audio/mpeg', 'audio/mp3', 'audio/wav', 'audio/xwav', 'audio/ogg']
))
{
return true;
}
else {
Storage::delete($value->getPathname());
};
}
}
public static function getRules() {
return array(
'user' => 'required|integer|max:255',
'size' => 'required|integer|max:15360',
'music' => 'required|max:15360|audio'
);
}