在 Laravel 8 / livewire 2 应用程序中,我添加了 spatie/laravel-medialibrary 9,当我使用方法进行选择的预览时
<input type="file" id="image" wire:change="$emit('fileChosen')">
...
Livewire.on('fileChosen', app_image_id => {
alert('fileChosen' + app_image_id);
let inputField = document.getElementById('image')
let file = inputField.files[0]
console.log('file::')
console.log(file)
let file_name = file.name
// console.log('file_name::')
// console.log(file_name)
let reader = new FileReader()
console.log('reader::')
console.log(reader)
//
reader.onloadend = () => {
window.livewire.emit('fileUpload', reader.result, file_name)
// console.log('reader.result::')
// console.log(reader.result)
}
reader.readAsDataURL(file)
})
public function handleFileUpload($imageData, $file_name)
{
$this->uploaded_file_name = $file_name;
$this->uploadedAppImageImage = $imageData;
}
结果在 uploadAppImageImage 中我有上传文件的内容,看起来像一个长字符串:
File `data:image/png;base64,iVBORw0KGg c TC4u3U1VaLKoOgg...mCC` AAAAElFTkSuQmCC` does not exists
但是查看用于添加图像的 laravel-medialibrary 方法 https://spatie.be/docs/laravel-medialibrary/v9/api/adding-files#addmediafromdisk 我看不到可以在 $uploadedAppImageImage 中使用哪种方法?
更新的第 1 部分: 我找到了方法 addMediaFromString (https://spatie.be/docs/laravel-medialibrary/v9/api/adding-files#addmediafromstring):
但是做一些测试我发现上传的图片是无效的。我尝试从 base64 解码(我在上面写了文件内容的样子)。我尝试了几种方法,例如:
->addMediaFromString( base64_decode( str_replace(' ','+',$this->uploadedAppImageImage)) )
->addMediaFromString( base64url_decode($this->uploadedAppImageImage) )
最后一种方法写在这里https://www.php.net/manual/ru/function.base64-decode.php为:
function base64url_decode($data) {
return base64_decode(str_replace(array('-', '_'), array('+', '/'), $data));
}
但无论如何上传的图片无效。我应该尝试哪种方法?
谢谢!