Laravel 5图像上传不正确的数据库路径

时间:2015-06-08 22:20:14

标签: php laravel laravel-5 upload

我的图片上传输入一直存在问题。我正在尝试在Laravel 5项目中创建文件上传输入,但是我遇到了保存到数据库映像表中的路径问题。

表单正在运行并且正在发布,但是,当数据库保存其输入的图像的路径时:/Applications/MAMP/tmp/php/phptvwTYW而不是仅使用文件名。

此外,该文件正被移动到正确的public/img文件夹。

代码

public function store(PostRequest $request)
{
    $this->createPost($request);

    $destinationpath = public_path() . '/img/';

    $filename = $request->file('image_url')->getClientOriginalName();

    $request->file('image_url')->move( $destinationpath,$filename );

    flash()->success('Your Post Has Been Created!');

    return redirect('posts');
}

6 个答案:

答案 0 :(得分:2)

以下是我项目中当前使用的示例控制器功能

public function postCreateInternal(CreateDocumentInternalRequest $request) {
        $data_information = $request->only(['title', 'assigned_to', 'folder_id', 'document_source']);
        if ($request->hasFile('file_name') && $request->file('file_name')->isValid()) {
            $document = $request->file('file_name');
            #creating file Name
            $mytime = Carbon::now();
            $date_now = $mytime->toDateTimeString();
            $date_now = $this->prepareFileNameString($date_now);
            $document_extension = $document->getClientOriginalExtension();

            $document_name = $this->prepareFileNameString(basename($document->getClientOriginalName(), '.' . $document_extension));
            $document_fullName = $document_name . "_" . ($date_now) . "." . $document_extension;
            $data_information['file_type'] = $document->getMimeType();
            $data_information['file_size'] = $document->getSize();
            $data_information['file_name'] = $document_fullName;
            $data_information['file_download_type'] = "Internal";
            $document->move(public_path() . '/uploads/documents/', $document_fullName);
        }
        if ($pot = $this->document->create($data_information)) {
            $this->notification_admin->sendCreateDocument($data_information);
            return redirect()->route('documents')->with('success', trans('document.create.msg_success'));
//          return redirect()->route('update/document', $pot->id)->with('success', trans('document.create.msg_success'));
        }
        return redirect()->route('create/document')->with('error', trans('document.msg_error'));
    }

CreateDocumentInternalRequest基本上用于Laravel 5的文件和其他数据验证

View File似乎喜欢:

{!! Form::open(["class"=>"form-horizontal","data-parsley-validate"=>"data-parsley-validate",'role'=>'form','files'=>true]) !!}
<div class="form-group  required {{ $errors->first('file_name', ' has-error') }}">
    {!!Form::label('file_name', trans('document.label.file_name'), array('class' => 'col-md-4 control-label left-label'))!!}
    <div class="col-sm-6">
        {!! Form::file('file_name') !!}
        {!! $errors->first('file_name', '<span class="help-block">:message</span>') !!}
    </div>
</div>
{!! Form::close() !!}

在我当前的实现中,首先我要检查上传的文件,用当前时间戳重命名文件名并重新上传我想要的位置。 如果您需要任何帮助,我提供的方法让我知道如何更好地改进。

答案 1 :(得分:1)

这是非常简单的方法:

public function store(PostRequest $request)
{
    $image_name = $request->file('image')->getClientOriginalName();
    $request->file('image')->move(base_path().'/public/images', $image_name);
    $post = ($request->except(['image']));
    $post['image'] = $image_name;
    Post::create($post);
    Session::flash('success_message', 'Post has been added successfully!');
    return redirect('teacher');
}

答案 2 :(得分:1)

  public function profileUpdate($id)
    {

    if(!Entrust::can('profile_update_employee'))
        return Redirect::to('/dashboard')->withErrors(Config::get('constants.NA'));

    if(!Helper::getMode())
        return Redirect::back()->withErrors(Config::get('constants.DISABLE_MESSAGE'));

    $employee = User::find($id);

    if(!$employee)
        return Redirect::to('employee')->withErrors(Config::get('constants.INVALID_LINK'));

    $rules = array(
        'photo' => 'image|image_size:<=2000|max:100000',
        'date_of_birth' => 'date',
        'date_of_joining' => 'date',
        'date_of_leaving' => 'date',
        'employee_code' => 'required|unique:profile,employee_code,'.$employee->Profile->id.',id'
    );


    $validator = Validator::make(Input::all(), $rules);

    if ($validator->fails())
        return Redirect::to('/employee/'.$id."#basic")->withErrors($validator);

    Activity::log('Profile updated');
    $profile = $employee->Profile ?: new Profile;
    $photo = $profile->photo;
    $data = Input::all();
    $profile->fill($data);
    if(Input::get('date_of_birth') == '')
        $profile->date_of_birth = null;
    if(Input::get('date_of_joining') == '')
        $profile->date_of_joining = null;
    if(Input::get('date_of_leaving') == '')
        $profile->date_of_leaving = null;

    if (Input::hasFile('photo') && Input::get('remove_photo') != 1) {


      $filename = Input::file('photo')->getClientOriginalName();
      $extension = Input::file('photo')->getClientOriginalExtension();
      $file = Input::file('photo')->move('assets/user/', $employee->username.".".$extension);

      DB::insert('insert into ez_profile (id, photo) values ($id, $photo)');

      $img = Image::make('assets/user/'.$user->username.".".$extension);
      $img->resize(200, null, function ($constraint) {
      $constraint->aspectRatio();
      });
      $img->save('assets/user/'.$user->username.".".$extension);
      $profile->photo = $employee->username.".".$extension;
      } elseif(Input::get('remove_photo') == 1){
      File::delete('assets/user/'.$profile->photo);
      $profile->photo = null;
      }
      else
      $profile->photo = $photo;
      $employee->profile()->save($profile);
      return Redirect::to('/employee/'.$id.'/#basic')->withSuccess(Config::get('constants.SAVED'));
      }

答案 3 :(得分:0)

试试这个:

public function store(PostRequest $request, Post $post) { 
    $destinationpath = public_path() . '/img/';

    $filename = $request->file('image_url')->getClientOriginalName();

    $request->file('image_url')->move( $destinationpath,$filename );

    $post->create([
        'field1' => $val1,
        'imageField' => $filename,
        'field2' => $val2
        ]);

    flash()->success('Your Post Has Been Created!');

    return redirect('posts');
}

答案 4 :(得分:0)

我找到了问题的解决方案。 我必须对我的控制器中的store和createPost函数进行一些更改才能使其工作。

对于控制器我有:

public function store(PostRequest $request)
{
        $destinationpath = public_path() . '/img/';

        $filename = $request->file('image_url')->getClientOriginalName();

        $request->file('image_url')->move( $destinationpath,$filename );

        $this->createPost($request, $filename);

        flash()->success('Your Post Has Been Created!');

        return redirect('posts');
}


private function createPost(PostRequest $request, $new_url)
{
        $post = Auth::user()->posts()->create($request->all());

        $post->image_url = $new_url;

        $post->save();

        $this->syncTags($post, $request->input('tag_list'));

        return $post;
}

我希望这可以帮助其他可能遇到同样问题的人。 谢谢大家的帮助!

答案 5 :(得分:-1)

因为你在搬家前保存,

//before moving 
$request->file('image_url')->getPath(); // returns Applications/MAMP/tmp/php/php...

要获得新移动文件的完整路径,您可以执行此操作

//After moving
$res = $request->file('image_url')->move( $destinationpath,$filename );
$my_new_path = $res->getPath(); // returns [public_path]/img/filename.jpg

您可以在移动文件后通过更新帖子来保存它,或者在保存时使用事件来移动它 看这里http://laravel.com/docs/master/eloquent#events