Laravel 文件上传混乱

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

    });

这是AccountController里面的方法:

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().

来获取授权用户的模型