问题描述
我在共享托管上更新更多图像时遇到问题,但在我的本地机器上一切正常
我在共享主机上遇到了这个错误。
file_put_contents(/public/storage/article_image/post_162069532710.png): Failed to open stream: No such file or directory
这是我的更新功能
$detail=$request->messageInput;
$dom = new \domdocument('1.0','UTF-8');
@$dom->loadHtml('<?xml encoding="UTF-8">'.$detail);
libxml_use_internal_errors(true);
$images = $dom->getelementsbytagname('img');
$bs64='base64';//variable to check the image is base64 or not
foreach($images as $k => $img){
$data = $img->getattribute('src');
if (strpos($data,$bs64) == true)//if the Image is base 64
{
$data = base64_decode(preg_replace('#^data:image/\w+;base64,#i','',$data));
$image_name = "/storage/article_image/". 'post_' . time() . $k . '.png';
$path = public_path() . $image_name;
file_put_contents($path,$data);
$img->removeAttribute('src');
$img->setAttribute('src',$image_name);
}
else
{
$image_name="".$data;
$img->setAttribute('src',$image_name);
}
};
$detail = $dom->savehtml();
$article=Article::find($id);
$article->articlecategory_id=$request->articlecategory_id;
$article->title=$request->title;
$article->keyword=$request->keyword;
$article->shortdetail=$request->shortdetail;
$article->fulldetail = $detail;
$article->updated_by=Auth::id();
$article->status_id=$request->status_id;
$article->save();
表单上传
<div class="mx-auto col-md-8">
{{csrf_field()}}
<textarea name="messageInput" class="summernote" minlength="300" maxlength="5100" required>{{$articles->fulldetail}}</textarea>
<span class="text-danger">{{ $errors->first('fulldetail') }}</span>
</div>
我已经坚持了大约 2 天。请帮助:[
解决方法
如果您尝试将文件放入不存在的目录中,
file_put_contents
将失败。在本地,您有目录 /public/storage/article_image/
,因此您不会收到此错误,但在共享主机中却不会。在将数据写入文件之前,您应该检查目录是否存在。
$data = base64_decode(preg_replace('#^data:image/\w+;base64,#i','',$data));
$dir = public_path() . "/storage/article_image";
if( !is_dir( $dir ) ) {
mkdir( $dir,0777,true );
}
$path = $dir. '/post_' . time() . $k . '.png';
file_put_contents($path,$data);