Laravel 5 Image Upload Incorrect Database Path

女生的网名这么多〃 提交于 2020-01-02 08:19:10

问题


I have been having issues with my image upload input. I am attempting to create a file upload input into my Laravel 5 project but I am running into problems with the path that is saved into the database image table.

The form is working and is posting, however, when the database saves the path to the image it is inputting: /Applications/MAMP/tmp/php/phptvwTYW instead of taking just the file name.

Additionally, the file is being moved to the correct public/img folder.

Code

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

回答1:


Here is the sample Controller Function currently using in my project

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 basically using for File and other data validation as per Laravel 5

And View File seems to like:

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

In my current implementation, first i'm checking file uploaded, rename filename with current timestamp and re upload my desire location. If you need any help my provided method let me know to improve in better way.




回答2:


this is very simple way:

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



回答3:


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



回答4:


Try this:

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



回答5:


I found the solution to my question. I had to make some changes to the store and createPost functions within my controller to make this work.

For the controller I have:

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

I hope this helps anyone else that may be running into this same problem. Thank you everyone for the help!




回答6:


its because you save before moving,

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

to have the full path of your new moved file you can do this

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

you can save it by update your post after moving the file, or use event to move it when saving look here http://laravel.com/docs/master/eloquent#events



来源:https://stackoverflow.com/questions/30720063/laravel-5-image-upload-incorrect-database-path

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!