0

我使用 laravel 5.6

我想一次上传 2 个文件夹中的文件。因此,如果图像在产品文件夹中成功上传,我希望图像也上传到 thumbs 文件夹中

我尝试这样:

public function uploadImage($file)   
{
    if($file) {
        $fileName = str_random(40) . '.' . $file->guessClientExtension();
    }

    $destinationPath = storage_path() . DIRECTORY_SEPARATOR . 'app' . DIRECTORY_SEPARATOR . 'public' . DIRECTORY_SEPARATOR . 'product';

    if(!File::exists($destinationPath)) {
        File::makeDirectory($destinationPath, 0755, true);
    }

    $file->move($destinationPath, $fileName);

    $destinationPathThumb = storage_path() . DIRECTORY_SEPARATOR . 'app' . DIRECTORY_SEPARATOR . 'public' . DIRECTORY_SEPARATOR . 'product' . DIRECTORY_SEPARATOR . 'thumb';

    if(!File::exists($destinationPathThumb)) {
        File::makeDirectory($destinationPathThumb, 0755, true);
    }

    $image_resize = Image::make($file->getRealPath());  
    $image_resize->resize(300, 300);
    $image_resize->save($destinationPathThumb . DIRECTORY_SEPARATOR . $fileName);

    return $fileName;
}

如果代码运行,则在产品文件夹中上传成功。它没有上传到拇指文件夹中

存在这样的错误:

消息无法找到文件 (/tmp/phpUSxbEJ)。

异常干预\图像\异常\NotReadableException

我尝试运行此代码:

public function uploadImage($file) 
{
    if($file) {
        $fileName = str_random(40) . '.' . $file->guessClientExtension();
    }
    $destinationPathThumb = storage_path() . DIRECTORY_SEPARATOR . 'app' . DIRECTORY_SEPARATOR . 'public' . DIRECTORY_SEPARATOR . 'product' . DIRECTORY_SEPARATOR . 'thumb';

    if(!File::exists($destinationPathThumb)) {
        File::makeDirectory($destinationPathThumb, 0755, true);
    }
    $image_resize = Image::make($file->getRealPath());  
    $image_resize->resize(300, 300);
    $image_resize->save($destinationPathThumb . DIRECTORY_SEPARATOR . $fileName);
    return $fileName;
}

所以我删除了要上传到产品文件夹中的代码。我试了一下,效果很好。它成功上传到拇指文件夹

所以我认为在一个过程中,它只上传到一个文件夹中

有没有其他方法可以上传 2 个文件夹?

4

2 回答 2

1

您首先上传将temporary file其保存在磁盘上后将被删除的内容,这就是为什么您不能重复使用它,而不是重复使用它,您获取保存的图像并对其进行调整大小并以不同的名称保存它:

public function uploadImage($file) 
{
...
$file->move($destinationPath, $fileName);
//$file here doesn't exist anymore, hence it can't be read
...
$uploadedFile = Storage::get($destinationPath . DIRECTORY_SEPARATOR . $filename);
$image_resize = Image::make($uploadedFile);  
$image_resize->resize(300, 300);
$image_resize->save($destinationPathThumb . DIRECTORY_SEPARATOR . $fileName);

return $fileName;
}
于 2018-02-24T10:57:16.387 回答
0

我找到了解决方案

我尝试这样:

$file = $file->move($destinationPath, $fileName);

有用

于 2018-02-25T03:18:03.187 回答