首页 > 解决方案 > Laravel将图像上传到Windows上的存储

问题描述

为了开发我在我的 laravel 项目上的 windows 上工作。我试图让文件上传在本地工作。

我的上传代码:

public function addPicture(Request $request, $id)
{
    $bathroom = Bathroom::withTrashed()->findOrFail($id);
    $validatedData = Validator::make($request->all(), [
        'afbeelding' => 'required|image|dimensions:min_width=400,min_height=400',
    ]);
    if($validatedData->fails())
    {
        return Response()->json([
            "success" => false,
            "errors" => $validatedData->errors()
        ]);
    }
    if ($file = $request->file('afbeelding')) {
        $img = Image::make($file);
        $img->resize(3000, 3000, function ($constraint) {
            $constraint->aspectRatio();
            $constraint->upsize();
        });
        $img->stream();
        $uid = Str::uuid();
        $fileName = Str::slug($bathroom->name . $uid).'.jpg';

        $this->createImage($img, 3000, "high", $bathroom->id, $fileName);
        $this->createImage($img, 1000, "med", $bathroom->id, $fileName);
        $this->createImage($img, 700, "thumb", $bathroom->id, $fileName);
        $this->createImage($img, 400, "small", $bathroom->id, $fileName);

        $picture = new Picture();
        $picture->url = '-';
        $picture->priority = '99';
        $picture->alt = Str::limit($bathroom->description,100);
        $picture->margin = 0;
        $picture->path = $fileName;
        $picture->bathroom_id = $id;
        $picture->save();

        return Response()->json([
            "success" => true,
            "image" => asset('/storage/img/bathroom/'.$id.'/small/'.$fileName),
            "id" => $picture->id
        ]);
    }
    return Response()->json([
        "success" => false,
        "image" => ''
    ]);
}

public function createImage($img, $size, $quality, $bathroomId, $fileName){
    $img->resize($size, $size, function ($constraint) {
        $constraint->aspectRatio();
        $constraint->upsize();
    });
    Storage::put(  $this->getUploadPath($bathroomId, $fileName, $quality), $img->stream('jpg',100));

}

public function  getUploadPath($bathroom_id, $filename, $quality = 'high'){
    $returnPath = asset('/storage/img/bathroom/'.$bathroom_id.'/'.$quality.'/'.$filename);
    echo $returnPath;

}

我确实运行了:php artisan storage:link

并且以下路径可用D:\Documents\repos\projectname\storage\app。当我上传文件时,我得到:

“消息”:“fopen(D:\Documents\repos\projectname\storage\app\):无法打开流:没有这样的文件或目录”,“异常”:“ErrorException”,“文件”:“D:\ Documents\repos\projectname\vendor\league\flysystem\src\Adapter\Local.php", "line": 157,

后来在日志中:

 "file": "D:\\Documents\\repos\\projectname\\app\\Http\\Controllers\\Admin\\BathroomController.php",
        "line": 141, . 

它指向以下行。

Storage::put(  $this->getUploadPath($bathroomId, $fileName, $quality), $img->stream('jpg',100));

createImage 函数。我怎样才能让它在 Windows 上工作,以便我可以在本地测试我的网站?

标签: phplaravel

解决方案


我希望你在这里使用图像干预。如果没有,您可以运行以下命令:

      composer require intervention/image

这将对您的项目进行干预。现在使用以下代码在本地上传图片。

您可以通过以下方式调用该函数来保存图像:

if ($request->hasFile('image')) {
   $image = $request->file('image');
   //Define upload path
   $destinationPath = public_path('/storage/img/bathroom/');//this will be created inside public folder
   $filename = round(microtime(true) * 1000) . "." .$image->getClientOriginalExtension();

  //upload file
  $this->uploadFile($image,$destinationPath,$filename,300,300);

//put your code to Save In Database
//just save the $filename in the db. 

//put your return statements here    


}

    


public function  uploadFile($file,$destinationPath,$filename,$height=null,$width=null){
    
//create folder if does not exist
if (!File::exists($destinationPath)){
   File::makeDirectory($destinationPath, 0777, true, true);
}
    
//Resize the image before upload using Image        Intervention
            
if($height!=null && $width!=null){
   $image_resize = Image::make($file->getRealPath());
   $image_resize->resize($width, $height);
   //Upload the resized image to the project path
   $image_resize->save($destinationPath.$filename);
}else{
     //upload the original image without resize. 
     $file->move($destinationPath,$filename);
     }
}

如果你还是想使用 Storage Facade,我在使用 Storage::put() 之前使用 Image->resize()->encode() 修改了你的代码。请查看以下代码是否有效。(抱歉,没时间测试)

public function addPicture(Request $request, $id)
{
  $bathroom = Bathroom::withTrashed()->findOrFail($id);
  $validatedData = Validator::make($request->all(), [
    'afbeelding' =>'required|image|dimensions:min_width=400,min_height=400']);
if($validatedData->fails())
{
    return Response()->json([
        "success" => false,
        "errors" => $validatedData->errors()
    ]);
}
if ($file = $request->file('afbeelding')) {
    $img = Image::make($file);
    $img->resize(3000, 3000, function ($constraint) {
        $constraint->aspectRatio();
        $constraint->upsize();
    });
    //Encode the image if you want to use Storage::put(),this is important step
    $img->encode('jpg',100);//default quality is 90,i passed 100
    $uid = Str::uuid();
    $fileName = Str::slug($bathroom->name . $uid).'.jpg';

    $this->createImage($img, 3000, "high", $bathroom->id, $fileName);
    $this->createImage($img, 1000, "med", $bathroom->id, $fileName);
    $this->createImage($img, 700, "thumb", $bathroom->id, $fileName);
    $this->createImage($img, 400, "small", $bathroom->id, $fileName);

    $picture = new Picture();
    $picture->url = '-';
    $picture->priority = '99';
    $picture->alt = Str::limit($bathroom->description,100);
    $picture->margin = 0;
    $picture->path = $fileName;
    $picture->bathroom_id = $id;
    $picture->save();

    return Response()->json([
        "success" => true,
        "image" => asset('/storage/img/bathroom/'.$id.'/small/'.$fileName),
        "id" => $picture->id
    ]);
}
return Response()->json([
    "success" => false,
    "image" => ''
]);
}
  public function createImage($img, $size, $quality, $bathroomId,$fileName){
$img->resize($size, $size, function ($constraint) {
    $constraint->aspectRatio();
    $constraint->upsize();
});
Storage::put(  $this->getUploadPath($bathroomId, $fileName, $quality), $img);

}
public function  getUploadPath($bathroom_id, $filename, $quality ='high'){
$returnPath = asset('/storage/img/bathroom/'.$bathroom_id.'/'.$quality.'/'.$filename);
return $returnPath; //changed echo to return

}

使用的来源:干预回购,Github

另外,请注意Storage的put方法适用于 Image Intervention 输出,而putFile方法适用于 Illuminate\Http\UploadedFile 以及 Illuminate\Http\File 和实例。


推荐阅读