Copy image to storage folder

2019-08-16 06:11发布

I'm trying copy an image to storage/app/uploads folder using the following code:

public function save(Request $request)
{
        $arrayName = array();
        echo "<pre>";
        print_r($request->all());
        echo "</pre>";

        $image = $request->file('image');
        $name = $imagem->getClientOriginalName();
        $ext = $imagem->getClientOriginalExtension();
        $newName = str_replace(' ','_', $imagem->getClientOriginalName());

        $destinationPath = 'uploads';
        //$path = $imagem->store($newName);
        $path = $imagem->storeAs($destinationPath, $newName);
        echo "<pre>";
        print_r($path);
        echo "</pre>";
}

The result from code above is:

Array
(
    [id] => 
    [description] => description
    [title] => title
    [title_small] => title_small
    [text] => text
    [image] => Illuminate\Http\UploadedFile Object
        (
            [test:Symfony\Component\HttpFoundation\File\UploadedFile:private] => 
            [originalName:Symfony\Component\HttpFoundation\File\UploadedFile:private] => manaus1.png
            [mimeType:Symfony\Component\HttpFoundation\File\UploadedFile:private] => application/octet-stream
            [error:Symfony\Component\HttpFoundation\File\UploadedFile:private] => 1
            [hashName:protected] => 
            [pathName:SplFileInfo:private] => 
            [fileName:SplFileInfo:private] => 
        )

    [published] => S
)

But when I open what has been saved, it open a text document with the original extension.

I want save the right way.

标签: php laravel
2条回答
我只想做你的唯一
2楼-- · 2019-08-16 06:56

I advise you to use this :

// SAME VALUES FROM THE FIRST ANSWER BUT WITH ANOTHER UPLOAD SYSTEM
if(Input::hasFile('imagen')) {
   $time = Carbon::now()->format('Y-m-d');
   $image = $request->file('imagen');
   $extension = $image->getClientOriginalExtension();
   $name = $image->getClientOriginalName();
   $fileName = $time."-".$name;
   // UPLOAD AND RUN YOUR SQL CODE IF YOU WANT ... 
   $path = \Storage::putFile('your_path', $image);
   # LARAVEL WILL GENRATE A UNIQUE FILE NAME ;) 
   return dd($path);

   // OR RETURN JSON RESPONSE IF YOU USE AJAX ;) 
   return response()->json([
     'title' => $fileName,
     'path' => $path,
     'status' => 'success'
   ]);
}
查看更多
再贱就再见
3楼-- · 2019-08-16 07:00

I'm saving with this code

if(Input::hasFile('imagen')) {
   $time = Carbon::now()->format('Y-m-d');
   $image = $request->file('imagen');
   $extension = $image->getClientOriginalExtension();
   $name = $image->getClientOriginalName();
   $fileName = $time."-".$name;
   $image->move(storage_path(),$fileName);
}

Please try this and let me know how it works. :)

查看更多
登录 后发表回答