【问题标题】:Cannot upload image in Laravel 5.2无法在 Laravel 5.2 中上传图片
【发布时间】:2018-04-17 00:24:08
【问题描述】:

我用上传图片制作输入数据,我的代码

$name   = $request->input('name');
$images = $request->file('image');
$name_img = $images->getClientOriginalName();
$ext = $images->getClientOriginalExtension();
// Move Uploaded File
$destinationPath = 'img/';
$images->move($destinationPath,$name_img);
$path = $destinationPath.'/'.$name_img;

然后将它们放入数组中,然后插入数据库中

$data = array(
'name' => $name,
'image' => $path, );
DB::table('daftar')->insert($data);
return json_encode(array('status' =>true));

该代码在 Laravel 5.1 中有效,但在 Laravel 5.2 中无效。

Laravel 5.2 的代码有什么问题吗?

谢谢。 :)

【问题讨论】:

  • 为什么有 2 个斜线?一个在'img/',一个在$path = $destinationPath.'/'.$name_img;
  • 我的意思是'img',没有斜线。

标签: php file-upload laravel-5.2 laravel-5.1 image-uploading


【解决方案1】:

我正在使用这种方法并且它有效:

//Use should have use App\Daftar in above your class;
//Your method inputs should be like UploadRequest $request , Daftar $daftar
$file=$request->file('image');
$name=time().'-'.$file->getClientOriginalName();
$path = public_path().'/img';
$file->move($path, $name);


$daftar->create(array('name' => $name, 'image' => $path));

确保表中没有不能为空的字段

您可以在此处了解有关 public_path() 的更多信息:

https://laravel.com/docs/5.5/helpers#method-public-path

我的上传文件夹也在公共目录中

如果您想确保保存在数据库中的数据与您发送的数据相同,请使用以下方法:

//Use should have use App\Daftar in above your class;
//Your method inputs should be like UploadRequest $request , Daftar $daftar
$file=$request->file('image');
$name=time().'-'.$file->getClientOriginalName();
$path = public_path().'/img';
$file->move($path, $name);

print 'name is'.$name.' and image is '.$path;

$daftar->create(array('name' => $name, 'image' => $path));

然后检查保存在数据库中的数据,两个数据应该相同。

【讨论】:

  • 如果我使用这种方法,我会像这样在数组中编写代码 $data = array( 'file' => $file, ); ,这是真的吗?
  • 感谢您的帮助。你给我的第一个方法是工作,但路径不正确,它去 /Applications/XAMPP/xamppfiles/temp/phpag1cVv。你的第一个方法是 $images=$request->file('image'); $name=time()."-".$images->getClientOriginalName(); $images->move(public_path().'/img',$name);
  • 你保存的路径在哪里,使用这种方法我将文件保存在公共/上传中
  • 我保存在 public/img
  • 所以将路径更改为 $path = public_path().'/img';
猜你喜欢
  • 1970-01-01
  • 2016-08-16
  • 2016-08-18
  • 2016-09-01
  • 2020-03-21
  • 2020-10-03
  • 2017-08-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多