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

        ]);

    }

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


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


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

创建图像函数。我怎样才能让它在 Windows 上运行,以便我可以在本地测试我的网站?


料青山看我应如是
浏览 145回答 3
3回答

慕桂英546537

我遇到过类似的问题并通过以下方式解决了要将文件上传到任何路径,请按照以下步骤操作。创建一个新磁盘config/filesystem.php并将其指向您喜欢的任何路径,例如D:/test或其他'disks' => [    // ...     'archive' => [            'driver' => 'local',            'root' => 'D:/test',         ],    // ...请记住archive磁盘名称,您可以将其调整为任何名称。之后做config:cache然后将文件上传到指定目录执行类似的操作  $request->file("image_file_identifier")->storeAs('SubFolderName', 'fileName', 'Disk');例如  $request->file("image_file")->storeAs('images', 'aa.jpg', 'archive');现在要获取文件,请使用以下代码      $path = 'D:\test\images\aa.jpg';    if (!\File::exists($path)) {        abort(404);    }    $file = \File::get($path);    $type = \File::mimeType($path);    $response = \Response::make($file, 200);    $response->header("Content-Type", $type);    return $response;

慕妹3146593

我通常直接将图像保存到公共文件夹这是我的项目之一的工作代码 $category = new Categories;//get icon path and moving it$iconName = time().'.'.request()->icon->getClientOriginalExtension(); // the icon in the line above indicates to the name of the icon's field in  //front-end$icon_path = '/public/category/icon/'.$iconName;//actually moving the icon to its destinationrequest()->icon->move(public_path('/category/icon/'), $iconName);  $category->icon = $icon_path;//save the image path to db $category->save();return redirect('/category/index')->with('success' , 'Category Stored Successfully');经过一些修改以适应您的代码,它应该可以正常工作

精慕HU

我希望你在这里使用图像干预。如果没有,您可以运行命令:      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 existif (!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}使用来源:Intervention repo,Github另请注意,Storage 的put方法适用于图像干预输出,而putFile方法适用于 Illuminate\Http\UploadedFile 以及 Illuminate\Http\File 和实例。
打开App,查看更多内容
随时随地看视频慕课网APP