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


Posted in PHP onNovember 14, 2019

首先先看下效果图

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

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实现图片上传预览,及编辑时可更换图片,并实时变化的例子就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

PHP 相关文章推荐
第五节--克隆
Nov 16 PHP
调试PHP程序的多种方法介绍
Nov 06 PHP
yii中widget的用法
Dec 03 PHP
PHP中使用register_shutdown_function函数截获fatal error示例
Apr 21 PHP
详解php中反射的应用
Mar 15 PHP
win10环境PHP 7 安装配置【教程】
May 09 PHP
PHP面向对象程序设计高级特性详解(接口,继承,抽象类,析构,克隆等)
Dec 02 PHP
MAC下通过改apache配置文件切换php多版本的方法
Apr 26 PHP
PHP 实现公历日期与农历日期的互转换
Sep 13 PHP
PHP一个简单的无需刷新爬虫
Jan 05 PHP
PHP中quotemeta()函数的用法讲解
Apr 04 PHP
解决在Laravel 中处理OPTIONS请求的问题
Oct 11 PHP
PHP实用小技巧之调用录像的方法
Dec 05 #PHP
Laravel框架控制器,视图及模型操作图文详解
Dec 04 #PHP
Laravel框架下载,安装及路由操作图文详解
Dec 04 #PHP
Laravel框架Eloquent ORM简介、模型建立及查询数据操作详解
Dec 04 #PHP
PHP实现二维数组(或多维数组)转换成一维数组的常见方法总结
Dec 04 #PHP
PHP实现提取多维数组指定一列的方法总结
Dec 04 #PHP
php实现快速对二维数组某一列进行组装的方法小结
Dec 04 #PHP
You might like
DOTA2 6.87版本后新眼位详解攻略
2020/04/20 DOTA
一个分页的论坛
2006/10/09 PHP
使用prototype.js 的时候应该特别注意的几个问题.
2007/04/12 Javascript
js保存当前路径(cookies记录)
2010/12/14 Javascript
javascript面向对象入门基础详细介绍
2012/09/05 Javascript
EditPlus注册码生成器(js代码实现)
2013/03/25 Javascript
由点击页面其它地方隐藏div所想到的jQuery的delegate
2013/08/29 Javascript
Jquery的hover方法让鼠标经过li时背景变色
2013/09/06 Javascript
Egret引擎开发指南之发布项目
2014/09/03 Javascript
JavaScript计算某一天是星期几的方法
2015/08/05 Javascript
JS实现页面跳转参数不丢失的方法
2016/11/28 Javascript
vue项目总结之文件夹结构配置详解
2017/12/13 Javascript
实例学习JavaScript读取和写入cookie
2018/01/29 Javascript
关于Mac下安装nodejs、npm和cnpm的教程
2018/04/11 NodeJs
获取layer.open弹出层的返回值方法
2018/08/20 Javascript
Vue实现table上下移动功能示例
2019/02/21 Javascript
vue实现多个echarts根据屏幕大小变化而变化实例
2020/07/19 Javascript
[02:41]DOTA2英雄基础教程 冥魂大帝
2014/01/16 DOTA
Python网络爬虫实例讲解
2016/04/28 Python
对python_discover方法遍历所有执行的用例详解
2019/02/13 Python
django创建超级用户时指定添加其它字段方式
2020/05/14 Python
python输入中文的实例方法
2020/09/14 Python
python collections模块的使用
2020/10/16 Python
解决python3.6用cx_Oracle库连接Oracle的问题
2020/12/07 Python
CSS3色彩模式有哪些?CSS3 HSL色彩模式的定义
2016/04/26 HTML / CSS
HTML5之SVG 2D入门3—文本与图像及渲染文本介绍
2013/01/30 HTML / CSS
关于.NET, HTML的五个问题
2012/08/29 面试题
生物化工专业个人自荐信
2013/09/26 职场文书
《雷鸣电闪波尔卡》教学反思
2014/02/23 职场文书
护理专业毕业生自荐书
2014/05/24 职场文书
企业宗旨标语
2014/06/10 职场文书
小升初自荐信怎么写
2015/03/26 职场文书
员工考勤管理制度
2015/08/06 职场文书
2016年基层党支部书记公开承诺书
2016/03/25 职场文书
浅谈MySQL user权限表
2021/06/18 MySQL
CSS 左边固定宽右边自适应的6种方法
2022/05/15 HTML / CSS