无法将图像上传到 Laravel 中的公共目录

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21854379/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 09:03:35  来源:igfitidea点击:

Can't upload images to a public directory in laravel

phplaravellaravel-4image-uploading

提问by cfkane

I'm trying to upload images into a Laravel app that will then need to be publicly displayed. However, I seem to only be able to upload to a folder within the application root. Any attempt to upload to the public directory throws the following error:

我正在尝试将图像上传到 Laravel 应用程序中,然后需要公开显示该应用程序。但是,我似乎只能上传到应用程序根目录中的文件夹。任何上传到公共目录的尝试都会引发以下错误:

protected function getTargetFile($directory, $name = null)
{
    if (!is_dir($directory)) {
        if (false === @mkdir($directory, 0777, true)) {
            throw new FileException(sprintf('Unable to create the "%s" directory', $directory));

I'm assuming this means that Laravel is going to prevent me from uploading to any file that is publicly accessible. I actually rather like this, however, how can I link to images that are outside of the public directory I've tried to ../ my way out of the public folder, but appropriately, that didn't work.

我假设这意味着 Laravel 将阻止我上传到任何可公开访问的文件。我实际上更喜欢这个,但是,我如何链接到公共目录之外的图像,我试图../我离开公共文件夹的方式,但适当地,这不起作用。

Alternately, anything that will let me uploaded directly to the public folder would be great too.

或者,任何能让我直接上传到公共文件夹的东西也很棒。

If it helps, here is my controller method that puts the file in public folder:

如果有帮助,这是我的控制器方法,它将文件放在公共文件夹中:

$thumbnail_file = Input::file('thumbnail'); 
$destinationPath = '/uploads/'. str_random(8);
$thumbnail_filename = $thumbnail_file->getClientOriginalName();
$uploadSuccess = Input::file('thumbnail_url')->move($destinationPath, $thumbnail_filename);

采纳答案by Steve Bauman

Your destination path should be:

您的目标路径应该是:

 $destinationPath = public_path(sprintf("\uploads\%s\", str_random(8)));

回答by vuhung3990

Route::post('upload', function(){
   $avarta = Input::file('avatar');
   if(strpos($avarta->getClientMimeType(),'image') !== FALSE){

      $upload_folder = '/assets/uploads/';

      $file_name = str_random(). '.' . $avarta->getClientOriginalExtension();

      $avarta->move(public_path() . $upload_folder, $file_name);

      echo URL::asset($upload_folder . $file_name);  // get upload file url

      return Response::make('Success', 200);
   }else{
     return Response::make('Avatar must be image', 400); // bad request
  }});

will upload to /public/assets/uploadsfolder, maybe help you

将上传到 /public/assets/uploads文件夹,也许对你有帮助

回答by Tongi

Try using this one in your controller after creating a folder called uploads in your public and another folder called photos in uploads.

在您的公共中创建一个名为uploads 的文件夹并在uploads 中创建另一个名为photos 的文件夹后,尝试在您的控制器中使用这个。

 $data = Input::all();
    $rules = array(           
        'photo' => 'between:1,5000|upload:image/gif,image/jpg,image/png,image/jpeg',            
    );
    $messages = array(
        'upload' => 'The :attribute must be one of the following types .jpg .gif .png .jpeg',
        'between' => 'The :attribute file size must be 1kb - 5mb'
    );

    $validator = Validator::make($data, $rules, $messages);
    if($validator->passes())
    {
        $uploads = public_path() . '/uploads/photos';
        $photo = Input::file('photo');
        $photodestinationPath = $uploads;

        $photoname = null;

        if($photo != null)
        {
            $photoname = $photo->getClientOriginalName();
            Input::file('photo')->move($photodestinationPath, $photoname);
        }

        $thumbnail = new Model_name();          
        $thumbnail ->column_name_in_table = $photoname;

and then put this in your routes

然后把它放在你的路线中

 Validator::extend('upload', function($attribute,$value, $parameters){
$count = 0;
for($i = 0; $i < count($parameters); $i++)
{
    if($value->getMimeType() == $parameters[$i])
    {
        $count++;
    }
}

if($count !=0)
{
    return true;
}
return false;});

回答by Cherma Ramalho

In the ImageProductController.php (Controller) file insert the following code:

在 ImageProductController.php (Controller) 文件中插入以下代码:

public function store(Request $request, $id)
{
if ($request->hasFile('image')){
  $rules = [
    'image'  => 'required|image|mimes:jpeg,png,jpg,gif,svg'
  ];

  $this->validate($request, $rules);

// Save file in directory
  $file = $request->file('image');
  $path = public_path() . '/images';
  $fileName = md5(rand(0,9999)).'.'.$file->getClientOriginalExtension();
  $file->move($path, $fileName);

  $imageProduct = new ImageProduct();
  $imageProduct->image = $fileName;
}

In the file create.blade.php (View) insert the following code:

在文件 create.blade.php (View) 中插入以下代码:

<form enctype="multipart/form-data" method="post" action=" " >
 {{ csrf_field() }}

      <label for="image" class="btn btn-primary">Inserir Imagem</label> 

      <input type="file" name="image" id="image"  accept="image/*" 
        class="form-control" value="{{ old('image') }}>   
</form>

In the ImageProduct.php file (Model) insert the following code:

在 ImageProduct.php 文件(模型)中插入以下代码:

public function getUrlAttribute()
{
    if(substr($this->image, 0, 4) === "http"){
        return $this->image;
    }

    return '/images/'.$this->image;
}

Good luck!

祝你好运!

回答by Zainul Abedin

You need to give permission the laravel folder where you want to store images. The commend is:

您需要授予要存储图像的 laravel 文件夹的权限。表扬的是:

sudo chown www-data:www-data /var/www/html/project-name/path/to/folder.

sudo chown www-data:www-data /var/www/html/project-name/path/to/folder.