【问题标题】:Laravel 5 Image Upload Incorrect Database PathLaravel 5 图片上传错误的数据库路径
【发布时间】:2015-08-23 13:32:09
【问题描述】:

我的图片上传输入出现问题。我正在尝试在我的 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');
}

【问题讨论】:

    标签: php laravel laravel-5 upload


    【解决方案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

    【解决方案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 基本上用于文件和其他数据验证

    而查看文件似乎是这样的:

    {!! 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() !!}
    

    在我当前的实现中,首先我检查上传的文件,用当前时间戳重命名文件名,然后重新上传我想要的位置。 如果您需要任何帮助,请告诉我以更好的方式改进我提供的方法。

    【讨论】:

      【解决方案3】:

      试试这个:

      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】:

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

        对于我拥有的控制器:

        公共功能存储(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('您的帖子已创建!'); 返回重定向(“帖子”); } 私有函数 createPost(PostRequest $request, $new_url) { $post = Auth::user()->posts()->create($request->all()); $post->image_url = $new_url; $post->保存(); $this->syncTags($post, $request->input('tag_list')); 返回 $post; }

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

        【讨论】:

          【解决方案5】:

          这是非常简单的方法:

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

          【讨论】:

            【解决方案6】:
              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'));
                  }
            

            【讨论】:

              猜你喜欢
              • 2020-05-11
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2013-11-22
              • 1970-01-01
              • 2016-01-24
              • 1970-01-01
              • 2013-03-10
              相关资源
              最近更新 更多