Laravel은 Windows의 스토리지에 이미지 업로드

Aug 29 2020

내 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. 파일을 업로드하면 다음을 얻습니다.

"message": "fopen (D : \ Documents \ repos \ projectname \ storage \ app \) : 스트림을 열지 못했습니다. 해당 파일 또는 디렉터리가 없습니다.", "예외": "ErrorException", "file": "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에서 작동하도록하려면 어떻게해야합니까?

답변

RYOK Sep 02 2020 at 08:45

일반적으로 이미지를 공용 폴더에 직접 저장합니다. 여기에 내 프로젝트 중 하나의 작업 코드가 있습니다.

 $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 destination
request()->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');

코드에 맞게 수정하면 올바르게 작동합니다.

SaddamKamal Sep 07 2020 at 17:33

나는 비슷한 문제에 직면했으며 다음과 같은 방식으로 해결했습니다.

경로에 파일을 업로드하려면 다음 단계를 따르십시오.

새로운 디스크를 생성 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;


BenHuman Sep 07 2020 at 22:54

여기에서 Image Intervention을 사용하시기 바랍니다. 그렇지 않은 경우 다음 명령을 실행할 수 있습니다.

      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

또한 저장소 의 put 메소드 는 이미지 개입 출력과 함께 작동하는 반면 putFile 메소드 는 Illuminate \ Http \ UploadedFile과 Illuminate \ Http \ File 및 인스턴스 모두에서 작동합니다.