我无法将文件上传的正确图像路径存储到数据库中。
这是我的代码:
public function store()
{
$input = Input::all();
try
{
$this->modelForm->validate($input);
if ( Input::hasFile('thumbnail')) {
$file = Input::file('thumbnail');
$name = time().'-'.$file->getClientOriginalName();
$file = $file->move('uploads/', $name);
$input['file'] = $file->getRealPath();
}
$model = new Model($input);
$model->save();
Redirect::back();
}
catch (FormValidationException $e)
{
return Redirect::back()->withInput()->withErrors($e->getErrors());
}
}
所以......这就是我用这段代码存储的内容:
/home/vagrant/code/website/public/uploads/1411468959-Bia.jpg
这就是我想要存储的东西:
public/uploads/1411468959-Bia.jpg
答案 0 :(得分:0)
你可以使用它:
public function store()
{
$input = Input::all();
try
{
$this->modelForm->validate($input);
if ( Input::hasFile('thumbnail')) {
$file = Input::file('thumbnail');
$name = time().'-'.$file->getClientOriginalName();
$file = $file->move('uploads/', $name);
$input['file'] = '/public/uploads/'.$name;
}
$model = new Model($input);
$model->save();
Redirect::back();
}
catch (FormValidationException $e)
{
return Redirect::back()->withInput()->withErrors($e->getErrors());
}
}
请注意,您可能也希望存储前导斜杠。
答案 1 :(得分:0)
好吧,你使用getRealPath,whitch返回文件的绝对路径。
我更喜欢将存储路径和存储网址设置为您的设置。
例如:
$storage_path = '/home/vagrant/code/website/public/uploads/';
$storage_url = 'http://storage.yourwebsite.com/uploads/';
然后将文件基名保存到数据库中(在您的情况下:“1411468959-Bia.jpg”);
上传时,您可以使用
$file->move($storage_path, $name);
当您需要网址时,您可以致电
echo $storage_url.$name;
通过这种方式,您的存储路径和网址将保持灵活性。数据库中的文件名就是你需要的一切。
答案 2 :(得分:0)
您也可以更改此行:
$input['file'] = $file->getRealPath();
成:
$path = $file->getRealPath();
$pos = strpos($path,'/public/');
if ($pos !== false) {
$path = substr($path, $pos + 1);
}
$input['file'] = $path;
答案 3 :(得分:0)
您确实需要将路径存储在数据库中吗?您只需存储图像名称并在视图展示器或模型中生成路径。
类似的东西:
public function getPathAttribute()
{
return 'public/uploads/' . $this->fileName);
}
或者更好地将上传路径存储为配置变量。如果您将来移动上传文件夹,这将使您更容易:
public function originalUrl()
{
return Config::get('assets.upload') . $this->fileName);
}
将文件移动到定义的上传路径:
$file = $file->move(Config::get('assets.upload'), $name);
答案 4 :(得分:0)
派对有点晚了,但Laravel有一个有用的asset()
Helper来生成资产公开网址:
$input[ 'file' ] = asset( '/uploads/' . $this->fileName );
答案 5 :(得分:0)
不是将图像路径存储到数据库,而是仅存储具有唯一ID的图像名称。这是最佳方法,可以正常工作。
$destinationPath = 'wisdom/company_images/logo/';
if(Input::Hasfile('image')){
$files = Input::file('image');
$filename = md5(uniqid()).'.'.$files->getClientOriginalExtension();
$ext = explode('.',$filename);
$ext = strtolower($ext[count($ext)-1]);
$upload_success = $files->move($destinationPath, $filename);
}else{
$filename = Input::get('upload_image','');
}