欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

laravel实现图片上传预览,及编辑时可更换图片,并实时变化的例子

程序员文章站 2023-01-04 09:11:23
首先先看下效果图 这是添加的时候 可以上传照片 这是编辑的时候 可以修改照片 代码部分: 先看控制器: /*** * 添加商户 * @retu...

首先先看下效果图

这是添加的时候 可以上传照片

laravel实现图片上传预览,及编辑时可更换图片,并实时变化的例子

这是编辑的时候 可以修改照片

laravel实现图片上传预览,及编辑时可更换图片,并实时变化的例子

代码部分:

先看控制器:

/***
   * 添加商户
   * @return \illuminate\contracts\view\factory|\illuminate\view\view
   */
  public function add()
  {
 
    $data = null;
    return _view('admin.merchant.merchant.edit', compact('data'));
  }
 
  /***
   * 添加商户
   * @return \illuminate\contracts\view\factory|\illuminate\view\view
   */
  public function store(storemenchantrequest $request)
  {
    //判断手机号是否重复 重复不能添加
    //后面开发可能会去掉这个判断
    $merchant = merchant::where('mobile', $request->mobile)->first();
    if (!empty($merchant)) {
      return back()->witherrors('该用户已存在');
    }
    $token = str_random(60);
    $api_token = $this->gettoken($token);
    $newmerchantdata = [
      'mobile' => $request->mobile,
      'api_token' => $api_token,
    ];
    db::begintransaction();
    $newmerchant = merchant::create($newmerchantdata);
    $newdata = [
      'merchant_id' => $newmerchant->id,//merchantid
      'merchant_principal' => $request->merchant_principal,//负责人
      'merchant_name' => $request->merchant_name,//商家名称
      'merchant_short_name' => $request->merchant_short_name,//商家简称
      'merchant_address' => $request->merchant_address,//商家地址
      'business_num' => $request->business_num,//注册号
      'business_address' => $request->business_address,//营业地址
      'business_name' => $request->business_name,//营业执照名称
      'business_person' => $request->person,//营业执照法人
      'identity_name' => $request->person,//身份证姓名
      'identity_num' => $request->identity_num,//身份证号
    ];
    //上传缩略图
    $input = $request->all();
    if (isset($input['file']) && is_object($input['file'])) {
 
      $file_name = save_image_file($input['file'], 'merchant_infos');
      if (!$file_name) {
        return back()->with('msg', '图片上传失败,请重试!');
      }
//      dd($file_name);
      $input['thumbnail'] = $file_name;
      unset($input['_token']);
      unset($input['file']);
    } else {
      return back()->with('msg', '请上传图片');
    }
    //上传内景图1
    if (isset($input['image1']) && is_object($input['image1'])) {
 
      $file_name_1 = save_image_file($input['image1'], 'merchant_infos');
      if (!$file_name_1) {
        return back()->with('msg', '图片上传失败,请重试!');
      }
 
      $input['interior_figure_one'] = $file_name_1;
      unset($input['_token']);
      unset($input['image1']);
    } else {
      return back()->with('msg', '请上传图片');
    }
    //上传内景图2
    if (isset($input['image2']) && is_object($input['image2'])) {
 
      $file_name_2 = save_image_file($input['image2'], 'merchant_infos');
      if (!$file_name_2) {
        return back()->with('msg', '图片上传失败,请重试!');
      }
      $input['interior_figure_two'] = $file_name_2;
      unset($input['_token']);
      unset($input['image2']);
    } else {
      return back()->with('msg', '请上传图片');
    }
    //上传内景图3
    if (isset($input['image3']) && is_object($input['image3'])) {
 
      $file_name_3 = save_image_file($input['image3'], 'merchant_infos');
      if (!$file_name_3) {
        return back()->with('msg', '图片上传失败,请重试!');
      }
      $input['interior_figure_three'] = $file_name_3;
      unset($input['_token']);
      unset($input['image3']);
    } else {
      return back()->with('msg', '请上传图片');
    }
 
    $merchantinfo = merchantinfo::where('merchant_id', $newmerchant->id)->first();
    if (!empty($merchantinfo)) {
      return back()->witherrors('该用户已录入信息');
    }
    $homestayinfo = homestayinfo::where('merchant_id', $newmerchant->id)->first();
    if (!empty($homestayinfo)) {
      return back()->witherrors('该用户已录入信息');
    }
    //录入商户信息
    $newdata['thumbnail'] = $input['thumbnail'];
    $newdata['interior_figure_one'] = $input['interior_figure_one'];
    $newdata['interior_figure_two'] = $input['interior_figure_two'];
    $newdata['interior_figure_three'] = $input['interior_figure_three'];
    $newdata['content'] = $input['content'];
    $newmerchantinfo = merchantinfo::create($newdata);
    $newhomestayinfo = homestayinfo::create($newdata);
    if ($newmerchantinfo && $newhomestayinfo && $newmerchant) {
      db::commit();
      admin_action_logs($newmerchant, "添加商户成功");
      return redirect()->route('admin.merchant.index')->with('msg', '添加成功');
    } else {
      db::rollback();
      return back()->witherrors('添加失败,请联系管理员');
    }
 
 
  }

这边封装了一个上传图片的方法,调用即可

**
 * 调用的文件中需要 use illuminate\support\facades\input; illuminate\support\facades\storage;
 * save_image_file 保存图片文件 ,存在storage::disk('uploads') 目录下
 * @var $file object 上传的图片文件,具体是在 request 中的 uploadedfile 类型的对象
 * @var $prefix_name string 可选保存的文件名前缀
 * @var $path string 文件路径
 * @return bool/string 如果通过验证 则返回在新的文件名
 */
if (!function_exists('save_image_file')) {
 
  function save_image_file(&$file, $prefix_name = '', $path = 'serve')
  {
    $file = isset($file) ? $file : null;
    if ($file != null && $file->isvalid()) {
      // 获取文件相关信息
      $originalname = $file->getclientoriginalname(); // 文件原名
      $ext = $file->getclientoriginalextension();   // 扩展名
      //dd($ext);
      $file->getclientoriginalname();
 
      if ($ext == "" && $file->getclientoriginalname() == 'blob') {
        $ext = 'png';
      }
      if (!preg_match('/jpg|png|gif$/is', $ext)) {
        return false;
      }
      //dd($file->getrealpath());
      $realpath = $file->getrealpath();  //临时文件的绝对路径
      $type = $file->getclientmimetype();   // image/jpeg
      // 上传文件
      $filename = $prefix_name . '-' . date('y-m-d-h-i-s') . '-' . uniqid() . '.' . $ext;
      //dd($filename);
      $bool = storage::disk($path)->put($filename, file_get_contents($realpath));
      if (!$bool) return false;
      return $filename;
    }
    return false;
  }
}

接下来是编辑时候 显示已经上传的图片 并且可以进行修改:

<div class="row">
  <div class="col-lg-6 col-sm-8 col-xs-12">
    <div class="panel panel-default">
      {{ form::open(['method'=>'post','route' => ['admin.merchant.add_img_store'],'enctype'=>'multipart/form-data']) }}
      <div class="panel-heading">商户图片</div>
      <div class="panel-body">
        <input type="hidden" name="id" value="{{$data->id}}">
        <div class=" form-group">
          <?php $hasurl = old_or_new_field('thumbnail', $data); ?>
          <div class="form-group {{!$hasurl or 'has-error'}} has-feedback">
            <label class="control-label" for="file">
              <span class="font-red">*</span>
              <span>缩略图:</span>
              <span class="font-gray">(宽高为120px:120px):</span>
            </label>
            <div class="input-group">
              @if( $hasurl )
                <input type="file" class="file-preview form-control" name="file" id="file" accept="image/*"
                    value="{{ old_or_new_field('thumbnail',$data) }}">
              @else
                <input type="file" class="file-preview form-control validate" name="file" required id="file"
                    accept="image/*"
                    value="{{ old_or_new_field('thumbnail',$data) }}">
              @endif
            </div>
          </div>
          <div class="file-preview-wrap">
            <img
                @if( old_or_new_field('thumbnail',$data) )
                src="{{asset('storage/serve').'/'.old_or_new_field('thumbnail',$data)}}" data-src="{{ asset('storage/serve'.old_or_new_img('thumbnail', $data, false))}}"
                @else
 
                src="{{asset('storage/serve').'/'. (isset($data->merchantinfo->thumbnail)?$data->merchantinfo->thumbnail:' ')}}" data-src="{{ asset('storage/serve').'/'. (isset($data->merchantinfo->thumbnail)?$data->merchantinfo->thumbnail:' ')}}"
                @endif
                id="file-preview" class="img-thumbnail" alt="图片预览" data-magnify="gallery">
 
          </div>
        </div>
        <div>
          <?php $hasurl = old_or_new_field('interior_figure_one', $data); ?>
          <div class="form-group {{!$hasurl or 'has-error'}} has-feedback">
            <label class="control-label" for="file">
              <span class="font-red">*</span>
              <span>内景图1:</span>
              <span class="font-gray">(宽高为375px:200px):</span>
            </label>
            <div class="input-group">
              @if( $hasurl )
                <input type="file" class="file-preview-second form-control" name="image1" id="image1" accept="image/*"
                    value="{{ old_or_new_field('interior_figure_one',$data) }}">
              @else
                <input type="file" class="file-preview-second form-control validate" name="image1" required id="image1"
                    accept="image/*"
                    value="{{ old_or_new_field('interior_figure_one',$data) }}">
              @endif
            </div>
          </div>
          <div class="file-preview-wrap">
            <img
                @if( old_or_new_field('interior_figure_one',$data) )
                src="{{asset('storage/serve').'/'.old_or_new_field('interior_figure_one',$data)}}" data-src="{{ asset('storage/serve'.old_or_new_img('interior_figure_one', $data, false))}}"
                @else
                src="{{asset('storage/serve').'/'.(isset($data->merchantinfo->interior_figure_one)?$data->merchantinfo->interior_figure_one:'')}}" data-src="{{ asset('storage/serve').'/'.(isset($data->merchantinfo->interior_figure_one)?$data->merchantinfo->interior_figure_one:'')}}"
 
                @endif
                width="375px" height="200px" id="file-preview-second" class="img-thumbnail" alt="图片预览" data-magnify="gallery">
          </div>
        </div>
        <div >
          <?php $hasurl = old_or_new_field('interior_figure_two', $data); ?>
          <div class="form-group {{!$hasurl or 'has-error'}} has-feedback">
            <label class="control-label" for="file">
              <span class="font-red">*</span>
              <span>内景图2:</span>
              <span class="font-gray">(宽高为375px:200px):</span>
            </label>
            <div class="input-group">
              @if( $hasurl )
                <input type="file" class="file-preview-third form-control" name="image2" id="image2" accept="image/*"
                    value="{{ old_or_new_field('interior_figure_two',$data) }}">
              @else
                <input type="file" class="file-preview-third form-control validate" name="image2" required id="image2"
                    accept="image/*"
                    value="{{ old_or_new_field('interior_figure_two',$data) }}">
              @endif
            </div>
          </div>
          <div class="file-preview-wrap">
            <img
                @if( old_or_new_field('interior_figure_two',$data) )
                {{--src="{{route('img.uploads.file',[old_or_new_field('url',$data)])}}"--}}
                src="{{asset('storage/serve').'/'.old_or_new_field('interior_figure_two',$data)}}" data-src="{{ asset('storage/serve'.old_or_new_img('interior_figure_two', $data, false))}}"
                @else
                src="{{asset('storage/serve').'/'.(isset($data->merchantinfo->interior_figure_two)?$data->merchantinfo->interior_figure_two:'')}}" data-src="{{ asset('storage/serve').'/'.(isset($data->merchantinfo->interior_figure_two)?$data->merchantinfo->interior_figure_two:'')}}"
                @endif
                width="375px" height="200px" id="file-preview-third" class="img-thumbnail" alt="图片预览" data-magnify="gallery">
          </div>
        </div>
        <div>
          <?php $hasurl = old_or_new_field('interior_figure_three', $data); ?>
          <div class="form-group {{!$hasurl or 'has-error'}} has-feedback">
            <label class="control-label" for="file">
              <span class="font-red">*</span>
              <span>缩略图3:</span>
              <span class="font-gray">(宽高为375px:200px):</span>
            </label>
            <div class="input-group">
              @if( $hasurl )
                <input type="file" class="file-preview-forth form-control" name="image3" id="image3" accept="image/*"
                    value="{{ old_or_new_field('interior_figure_three',$data) }}">
              @else
                <input type="file" class="file-preview-forth form-control validate" name="image3" required id="image3"
                    accept="image/*"
                    value="{{ old_or_new_field('interior_figure_three',$data) }}" >
              @endif
            </div>
          </div>
          <div class="file-preview-wrap">
            <img
                @if( old_or_new_field('interior_figure_three',$data) )
                {{--src="{{route('img.uploads.file',[old_or_new_field('url',$data)])}}"--}}
                src="{{asset('storage/serve').'/'.old_or_new_field('interior_figure_three',$data)}}" data-src="{{ asset('storage/serve'.old_or_new_img('interior_figure_three', $data, false))}}"
                @else
                src="{{asset('storage/serve').'/'.(isset($data->merchantinfo->interior_figure_three)?$data->merchantinfo->interior_figure_three:'')}}" data-src="{{ asset('storage/serve').'/'.(isset($data->merchantinfo->interior_figure_three)?$data->merchantinfo->interior_figure_three:'')}}"
                @endif
                width="375px" height="200px" id="file-preview-forth" class="img-thumbnail" alt="图片预览" data-magnify="gallery">
          </div>
        </div>
      </div>
 
      <div class="text-center margin-bottom-sm">
        <button class="pretty-btn"> 编辑商户</button>
      </div>
      {{ form::close() }}
    </div>
  </div>
</div>

编辑这边 的控制器代码是:

/***
 * 添加图片
 * @return \illuminate\contracts\view\factory|\illuminate\view\view
 */
public function add_img()
{
  $data = null;
  return _view('admin.merchant.merchant.add', compact('data'));
}
 
/***
 * 保存图片
 * @return \illuminate\contracts\view\factory|\illuminate\view\view
 */
public function add_img_store(request $request)
{
  //上传缩略图
  $input = $request->all();
 
  if (isset($input['file']) && is_object($input['file'])) {
 
    $file_name = save_image_file($input['file'], 'merchant_infos');
    if (!$file_name) {
      return back()->with('msg', '图片上传失败,请重试!');
    }
 
    $input['thumbnail'] = $file_name;
    unset($input['_token']);
    unset($input['file']);
  } else {
    return back()->with('msg', '请上传图片');
  }
  //上传内景图1
  if (isset($input['image1']) && is_object($input['image1'])) {
 
    $file_name_1 = save_image_file($input['image1'], 'merchant_infos');
    if (!$file_name_1) {
      return back()->with('msg', '图片上传失败,请重试!');
    }
 
    $input['interior_figure_one'] = $file_name_1;
    unset($input['_token']);
    unset($input['image1']);
  } else {
    return back()->with('msg', '请上传图片');
  }
  //上传内景图2
  if (isset($input['image2']) && is_object($input['image2'])) {
 
    $file_name_2 = save_image_file($input['image2'], 'merchant_infos');
    if (!$file_name_2) {
      return back()->with('msg', '图片上传失败,请重试!');
    }
    $input['interior_figure_two'] = $file_name_2;
    unset($input['_token']);
    unset($input['image2']);
  } else {
    return back()->with('msg', '请上传图片');
  }
  //上传内景图3
  if (isset($input['image3']) && is_object($input['image3'])) {
 
    $file_name_3 = save_image_file($input['image3'], 'merchant_infos');
    if (!$file_name_3) {
      return back()->with('msg', '图片上传失败,请重试!');
    }
    $input['interior_figure_three'] = $file_name_3;
    unset($input['_token']);
    unset($input['image3']);
  } else {
    return back()->with('msg', '请上传图片');
  }
  //录入商户信息
 
  $merchang_info = merchantinfo::where('merchant_id', '=', $input['id'])->first();
  if (empty($merchang_info)) {
    $newdata['thumbnail'] = $input['thumbnail'];
    $newdata['merchant_id'] = $input['id'];
    $newdata['interior_figure_one'] = $input['interior_figure_one'];
    $newdata['interior_figure_two'] = $input['interior_figure_two'];
    $newdata['interior_figure_three'] = $input['interior_figure_three'];
    $newdata['content']='';
    $result = merchantinfo::create($newdata);
  } /* $newdata['thumbnail']=$input['thumbnail'];
  $newdata['interior_figure_one']=$input['interior_figure_one'];
  $newdata['interior_figure_two']=$input['interior_figure_two'];
  $newdata['interior_figure_three']=$input['interior_figure_three'];
  // $newdata['content']=$input['content'];
  $newmerchantinfo = merchantinfo::create($newdata);*/
  else {
    $merchang_info->thumbnail = $input['thumbnail']??'';
    $merchang_info->interior_figure_one = $input['interior_figure_one']??'';
    $merchang_info->interior_figure_two = $input['interior_figure_two']??'';
    $merchang_info->interior_figure_three = $input['interior_figure_three']??'';
    $result = $merchang_info->save();
  }
  if ($result) {
    db::commit();
    admin_action_logs($result, "编辑商户成功");
    return redirect()->route('admin.merchant.index')->with('msg', '编辑成功');
  } else {
    db::rollback();
    return back()->witherrors('编辑失败,请联系管理员');
  }
}

以上这篇laravel实现图片上传预览,及编辑时可更换图片,并实时变化的例子就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。