Laravel 5.2文件上传始终(/ tmp)保存在DB

时间:2016-12-15 14:18:01

标签: laravel laravel-5.2

我的代码如下,它成功地将文件移动到所需的路径中。我的问题是在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());

2 个答案:

答案 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/');
]);