拉拉维尔文件上传混乱


Laravel file upload confusion

所以,我试图在Laravel框架中与旧文件上传作斗争,但有点迷失。我已经设法让上传工作,因此文件上传并保存到具有随机字符串名称的资产文件夹中。

这是形式:

<form action="{{ URL::route('account-upload') }}" method="post">
{{ Form::label('file','Upload File') }}
{{ Form::file('file') }}
<br />
{{ Form::submit('Upload') }}
{{ Form::token() }}
</form>

这是路线:

Route::get('/account/upload', array(
    'as' => 'account-upload',
    'uses' => 'AccountController@getUpload'
));

    Route::post('/account/upload', function(){
        if (Input::hasFile('file')){
            $dest = 'assets/uploads/';
            $name = str_random(6).'_'. Input::file('file')->getClientOriginalName();
            Input::file('file')->move($dest,$name);
            return Redirect::to('/account/upload')
                ->withGlobal('Your image has been uploaded');
        }
    });

这是帐户控制器中的方法:

public function getUpload(){
    return View::make('account.upload');
}
public function postUpload() {
     $user  = User::find(Auth::id());
     $user->image  = Input::get('file');
}

我现在正在尝试启用它以将字符串名称推送到数据库中,并与上传它并显示为其个人资料图像的用户相关联?哎呀,指针会很棒!

我在数据库中创建了一个名为"file"的行,其文本类型....在这一点上,我不确定如何存储和查看图像。

试试这个

// the view
{{ Form::open(['route' => 'account-upload', 'files' => true]) }}
    {{ Form::label('file','Upload File') }}
    {{ Form::file('file') }}
    <br />
    {{ Form::submit('Upload') }}
{{ Form::close() }}

// route.php
Route::get('/account/upload', 'AccountController@upload');
Route::post('/account/upload', [
    'as'   => 'account-upload',
    'uses' => 'AccountController@store'
]);

// AccountController.php
class AccountController extends BaseController {
    public function upload(){
        return View::make('account.upload');
    }
    public function store() {
        if (Input::hasFile('file')){
            $file = Input::file('file');
            $dest = public_path().'/assets/uploads/';
            $name = str_random(6).'_'. $file->getClientOriginalName();
            $file->move($dest,$name);
            $user      = User::find(Auth::id());
            $user->image  = $name;
            $user->save();
            return Redirect::back()
                ->withGlobal('Your image has been uploaded');
        }
    }
}
// and to display the img on the view
<img src="assets/upload/{{Auth::user()->image}}"/>

为了上传文件,您需要enctype="multipart/form-data"作为<form>元素的属性。

如果您使用的是Form::open()方法,则可以在此处传递"files" => true,但这应该可以让您正确使用Input::file()

接下来,在实际处理文件时,您需要使用 storage_path()public_path() 之类的东西,并在移动文件时提供文件目标的绝对路径。

还有一个提示:您可以通过调用 Auth::user() 来获取经过身份验证的用户的模型。