Laravel文件上传混乱

时间:2015-02-01 22:35:59

标签: php laravel file-upload

所以,我正在尝试与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');
        }

    });

这是AccountController中的方法:

public function getUpload(){
    return View::make('account.upload');
}

public function postUpload() {
     $user  = User::find(Auth::id());
     $user->image  = Input::get('file');
}

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

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

2 个答案:

答案 0 :(得分:3)

试试这个

// 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}}"/>

答案 1 :(得分:2)

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

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

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

提示:您可以通过调用Auth::user()来获取authed用户的模型。