laravel 5.4上传图片

时间:2017-03-13 01:26:55

标签: php 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) {

        }
    }
}

图片已成功上传,但代码引发了异常:

  

MimeTypeGuesser.php第123行中的FileNotFoundException

该文件在我的代码中是否存在任何错误,或者它是laravel 5.4中的错误,有人可以帮我解决问题吗?

我的观看代码:

<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>

11 个答案:

答案 0 :(得分:32)

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

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');
    }
}

答案 1 :(得分:20)

您可以通过控制器中的store方法轻松使用它

如下所示

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

{{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()}}

以下是我们如何处理控制器中的文件。

<?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);

  }
}

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

答案 2 :(得分:4)

使用以下代码:

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

答案 3 :(得分:4)

您的应用程序的良好逻辑可能是:

 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');
      }

    }

答案 4 :(得分:3)

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');
}

答案 5 :(得分:1)

此代码会将图像存储在数据库中。

$('#image').change(function(){
        // FileReader function for read the file.
        let reader = new FileReader();
        var base64;
        reader.readAsDataURL(this.files[0]); 

        //Read File
        let filereader = new FileReader();
        var selectedFile = this.files[0];

        // Onload of file read the file content
        filereader.onload = function(fileLoadedEvent) {
            base64 = fileLoadedEvent.target.result;
            $("#pimage").val(JSON.stringify(base64));
        };

        filereader.readAsDataURL(selectedFile); 
 });

HTML内容应该是这样的。

<div class="col-xs-12 col-sm-4 col-md-4 user_frm form-group">
        <input id="image" type="file" class="inputMaterial" name="image">        
        <input type="hidden" id="pimage" name="pimage" value="">
        <span class="bar"></span>
    </div>

像这样在数据库中存储图像数据:

//property_image longtext(database field type)

 $data= array(
      'property_image' => trim($request->get('pimage'),'"')
 );

显示图像:

<img src="{{$result->property_image}}" >

答案 6 :(得分:0)

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) {

        }
    } 
}

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

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

答案 7 :(得分:0)

我认为最好这样做

    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);

实际上图像是laravel自动生成的文件夹,文件是输入的名称,这里我们在表和存储的路径列中存储图像的名称公共/图像目录中的图像

答案 8 :(得分:0)

// 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);
}

答案 9 :(得分:0)

干预图像是一个开放源代码的PHP图像处理和操作库 http://image.intervention.io/

  

该库提供了许多有用的功能:

基本示例

// 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');

方法链接:

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

提示:(根据您的情况)     https://laracasts.com/discuss/channels/laravel/file-upload-isvalid-returns-false

提示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
};

提示2:

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

功能

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(); //
   }
}

答案 10 :(得分:-1)

在Laravel 5.4中,您可以使用guessClientExtension