我的代码如下,它成功地将文件移动到所需的路径中。我的问题是在db中它总是像(/ tmp / phpI9zJ1F)一样在tmp /之后保存随机字符。我该如何解决这个问题?
$quiz = Quiz::findOrFail($id);
$tmp = '';
if( $request->hasFile('survey_image') )
{
$extension = $request->file('survey_image')->getClientOriginalExtension();
do{
$rand = rand(11111,99999);
$imageName = $rand.'.'.$extension;
$tmp = $imageName;
$is_duplicate = Quiz::where('survey_image', $imageName)->count();
}
while( $is_duplicate!=0 );
$request['survey_image'] = (string)$tmp;
$quiz->survey_image_path = 'images/surveys/';
}
$request->file('survey_image')->move(
'images/surveys/' , $tmp);
$quiz->update($request->all());
答案 0 :(得分:1)
您需要使用replace()
或merge()
才能覆盖$request
中的值。
$request->replace(array('survey_image' => (string)$tmp));
答案 1 :(得分:1)
你没有解释过很多,但我相信这是一种只更新图像的方法。
所以,我会做那样的事情:
$quiz = Quiz::findOrFail($id);
$tmp = '';
if( $request->hasFile('survey_image') )
{
$extension = $request->file('survey_image')->getClientOriginalExtension();
do{
$rand = rand(11111,99999);
$imageName = $rand.'.'.$extension;
$tmp = $imageName;
$is_duplicate = Quiz::where('survey_image', $imageName)->count();
}
while( $is_duplicate!=0 );
$request['survey_image'] = (string)$tmp;
$quiz->survey_image_path = 'images/surveys/';
$request->file('survey_image')->move(
$quiz->survey_image_path , $tmp);
$quiz->update([
'survey_image' => '/'.$quiz->survey_image_path.$imageName,
]);
}
如果您想重复使用代码,可以执行以下操作:(Ps。代码未经过测试!)
/**
* Handle File Upload
* @param UploadedFile $file [File from request]
* @param string $path [Path where to save the file]
* @param string|boolean $current_file [An old file that you want to delete, before save the new one]
* @return string
*/
public function updateImage(UploadedFile $file, $path, $current_file = false)
{
//Set a random name to the file
$extension = $file->getClientOriginalExtension();
$fileName = str_random(32) . '.' . $extension;
//Delete an old file first
if ($current_file !== false)
if (File::exists($current_file))
File::delete($current_file);
//Move new file to the directory
$file->move($path, $fileName);
return '/'.$path.$imageName;
}
您想要保存在数据库中的位置:
if( !$request->hasFile('survey_image') ) return false; //Or what you want
$quiz = Quiz::findOrFail($id);
$quiz->update([
'survey_image' => $this->updateImage(request('survey_image'), 'images/surveys/');
]);