php laravel 5.4 上传图片

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42755302/
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-08-26 02:42:16  来源:igfitidea点击:

laravel 5.4 upload image

phplaravel-5.4

提问by Sawung Himawan

My controller code for upload file in laravel 5.4:

我在 Laravel 5.4 中上传文件的控制器代码:

if ($request->hasFile('input_img')) {
    if($request->file('input_img')->isValid()) {
        try {
            $file = $request->file('input_img');
            $name = rand(11111, 99999) . '.' . $file->getClientOriginalExtension();
            $request->file('input_img')->move("fotoupload", $name);
        } catch (Illuminate\Filesystem\FileNotFoundException $e) {

        }
    }
}

Image was successfully uploaded but the code threw an exception :

图片已成功上传,但代码抛出异常:

FileNotFoundException in MimeTypeGuesser.php line 123

MimeTypeGuesser.php 第 123 行中的 FileNotFoundException

The file is there any fault in my code or is it a bug in laravel 5.4, can anyone help me solve the problem ?

该文件是我的代码中有任何错误还是laravel 5.4中的错误,有人可以帮我解决问题吗?

My view code:

我的查看代码:

<form enctype="multipart/form-data" method="post" action="{{url('admin/post/insert')}}">
    {{ csrf_field() }}
    <div class="form-group">
        <label for="imageInput">File input</label>
        <input data-preview="#preview" name="input_img" type="file" id="imageInput">
        <img class="col-sm-6" id="preview"  src="">
        <p class="help-block">Example block-level help text here.</p>
    </div>
    <div class="form-group">
        <label for="">submit</label>
        <input class="form-control" type="submit">
    </div>
</form>

回答by Rocky

Try this code. This will solve your problem.

试试这个代码。这将解决您的问题。

public function fileUpload(Request $request) {
    $this->validate($request, [
        'input_img' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
    ]);

    if ($request->hasFile('input_img')) {
        $image = $request->file('input_img');
        $name = time().'.'.$image->getClientOriginalExtension();
        $destinationPath = public_path('/images');
        $image->move($destinationPath, $name);
        $this->save();

        return back()->with('success','Image Upload successfully');
    }
}

回答by Emad Adly

You can use it by easy way, through storemethod in your controller

您可以通过store控制器中的方法以简单的方式使用它

like the below

像下面这样

First, we must create a form with file input to let us upload our file.

首先,我们必须创建一个带有文件输入的表单来让我们上传我们的文件。

{{Form::open(['route' => 'user.store', 'files' => true])}}

{{Form::label('user_photo', 'User Photo',['class' => 'control-label'])}}
{{Form::file('user_photo')}}
{{Form::submit('Save', ['class' => 'btn btn-success'])}}

{{Form::close()}}

Here is how we can handle file in our controller.

这是我们如何在控制器中处理文件。

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class UserController extends Controller
{

  public function store(Request $request)
  {

  // get current time and append the upload file extension to it,
  // then put that name to $photoName variable.
  $photoName = time().'.'.$request->user_photo->getClientOriginalExtension();

  /*
  talk the select file and move it public directory and make avatars
  folder if doesn't exsit then give it that unique name.
  */
  $request->user_photo->move(public_path('avatars'), $photoName);

  }
}

That's it. Now you can save the $photoNameto the database as a user_photofield value. You can use asset(‘avatars')function in your view and access the photos.

就是这样。现在您可以将 保存$photoName到数据库中作为user_photo字段值。您可以asset(‘avatars')在视图中使用功能并访问照片。

回答by SMK

Use the following code:

使用以下代码:

$imageName = time().'.'.$request->input_img->getClientOriginalExtension();
$request->input_img->move(public_path('fotoupload'), $imageName);

回答by ThiagoDeveloper

A good logic for your application could be something like:

您的应用程序的一个好的逻辑可能是这样的:

 public function uploadGalery(Request $request){
      $this->validate($request, [
        'file' => 'required|image|mimes:jpeg,png,jpg,bmp,gif,svg|max:2048',
      ]);
      if ($request->hasFile('file')) {
        $image = $request->file('file');
        $name = time().'.'.$image->getClientOriginalExtension();
        $destinationPath = public_path('/storage/galeryImages/');
        $image->move($destinationPath, $name);
        $this->save();
        return back()->with('success','Image Upload successfully');
      }

    }

回答by ayzeetech

public function store()
{
    $this->validate(request(), [
        'title' => 'required',
        'slug' => 'required',
        'file' => 'required|image|mimes:jpg,jpeg,png,gif'
    ]);

    $fileName = null;
    if (request()->hasFile('file')) {
        $file = request()->file('file');
        $fileName = md5($file->getClientOriginalName() . time()) . "." . $file->getClientOriginalExtension();
        $file->move('./uploads/categories/', $fileName);    
    }

    Category::create([
        'title' => request()->get('title'),
        'slug' => str_slug(request()->get('slug')),
        'description' => request()->get('description'),
        'category_img' => $fileName,
        'category_status' => 'DEACTIVE'
    ]);

    return redirect()->to('/admin/category');
}

回答by venkatskpi

Intervention Image is an open source PHP image handling and manipulation libraryhttp://image.intervention.io/

Intervention Image 是一个开源的 PHP 图像处理和操作库http://image.intervention.io/

This library provides a lot of useful features:

这个库提供了很多有用的功能:

Basic Examples

基本示例

// open an image file
$img = Image::make('public/foo.jpg');

// now you are able to resize the instance
$img->resize(320, 240);

// and insert a watermark for example
$img->insert('public/watermark.png');

// finally we save the image as a new file
$img->save('public/bar.jpg');

Method chaining:

方法链:

$img = Image::make('public/foo.jpg')->resize(320, 240)->insert('public/watermark.png');

Tips: (In your case)https://laracasts.com/discuss/channels/laravel/file-upload-isvalid-returns-false

提示:(在你的情况下)https://laracasts.com/discuss/channels/laravel/file-upload-isvalid-returns-false

Tips 1:

提示1:

// Tell the validator input file should be an image & check this validation
$rules = array(
  'image' => 'mimes:jpeg,jpg,png,gif,svg  // allowed type
              |required                  // is required field
              |max:2048'               // max 2MB
              |min:1024               // min 1MB
  );
// validator Rules
$validator = Validator::make($request->only('image'), $rules);

// Check validation (fail or pass)
if ($validator->fails())
{
    //Error do your staff
} else
{
    //Success do your staff
};

Tips 2:

提示2:

   $this->validate($request, [
        'input_img' => 
                 'required
                  |image
                  |mimes:jpeg,png,jpg,gif,svg
                  |max:1024',
    ]);

Function:

功能:

function imageUpload(Request $request) {

   if ($request->hasFile('input_img')) {  //check the file present or not
       $image = $request->file('input_img'); //get the file
       $name = "//what every you want concatenate".'.'.$image->getClientOriginalExtension(); //get the  file extention
       $destinationPath = public_path('/images'); //public path folder dir
       $image->move($destinationPath, $name);  //mve to destination you mentioned 
       $image->save(); //
   }
}

回答by Seyed Alireza Ghoreishi

i think better to do this

我认为最好这样做

    if ( $request->hasFile('file')){
        if ($request->file('file')->isValid()){
            $file = $request->file('file');
            $name = $file->getClientOriginalName();
            $file->move('images' , $name);
            $inputs = $request->all();
            $inputs['path'] = $name;
        }
    }
    Post::create($inputs);

actually imagesis folder that laravel make it automatic and fileis name of the input and here we store name of the image in our path column in the table and store image in public/images directory

实际上images是laravel使其自动的文件夹,file是输入的名称,在这里我们将图像的名称存储在表的路径列中,并将图像存储在public/images目录中

回答by akram

// get image from upload-image page 
public function postUplodeImage(Request $request)
{
    $this->validate($request, [
  // check validtion for image or file
        'uplode_image_file' => 'required|image|mimes:jpg,png,jpeg,gif,svg|max:2048',
    ]);
// rename image name or file name 

    $getimageName = time().'.'.$request->uplode_image_file->getClientOriginalExtension();
    $request->uplode_image_file->move(public_path('images'), $getimageName);
    return back()
        ->with('success','images Has been You uploaded successfully.')
        ->with('image',$getimageName);
}

回答by Talemul Islam

if ($request->hasFile('input_img')) {
    if($request->file('input_img')->isValid()) {
        try {
            $file = $request->file('input_img');
            $name = time() . '.' . $file->getClientOriginalExtension();

            $request->file('input_img')->move("fotoupload", $name);
        } catch (Illuminate\Filesystem\FileNotFoundException $e) {

        }
    } 
}

or follow
https://laracasts.com/discuss/channels/laravel/image-upload-file-does-not-working
or
https://laracasts.com/series/whats-new-in-laravel-5-3/episodes/12

或关注
https://laracasts.com/discuss/channels/laravel/image-upload-file-does-not-working

https://laracasts.com/series/whats-new-in-laravel-5-3/集数/12

回答by omdjin

In Laravel 5.4, you can use guessClientExtension

在 Laravel 5.4 中,您可以使用 guessClientExtension