laravel图片和文件的上传

获取表单传来的图片有两种方式

    $file = $request::file('picfile');
    或者
    $request = $request::all(); //注意先先取全,得到的是数组 
    $file = $request['picfile'];

1.前端页面

  {{--<form action="upload" method="POST" enctype="multipart/form-data" >--}}
    <input type="text" size="50" name="art_thumb">
    <input id="file_upload" name="file_upload" type="file" multiple="true">
        {{ csrf_field() }}
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
    <script src="{{asset('uploadify/jquery.uploadify.min.js')}}" type="text/javascript"></script>
    <link rel="stylesheet" type="text/css" href="{{asset('uploadify/uploadify.css')}}">
    <script type="text/javascript">
        <?php $timestamp = time();?>
        $(function() {
            $('#file_upload').uploadify({
                'buttonText' : '12图片上传',
                'formData'     : {
                    'timestamp' : '<?php echo $timestamp;?>',
                    '_token'     : "{{csrf_token()}}"
                },
                'swf'      : "{{asset('uploadify/uploadify.swf')}}",
                'uploader' : "{{url('/addpic')}}",   //这个是提交图片处理的地址
                'onUploadSuccess' : function(file, data, response) {
                    $('input[name=art_thumb]').val(data);
                    $('#art_thumb_img').attr('src',data);
    //                                    alert(data);
                }
            });
        });
    </script>
    <style>
        .uploadify{display:inline-block;}
        .uploadify-button{border:none; border-radius:5px; margin-top:8px;}
        table.add_tab tr td span.uploadify-button-text{color: #FFF; margin:0;}
    </style>
    <button>ok</button>
    {{--</form>--}}
    <img src="" alt="" id="art_thumb_img" style="max-width: 350px; max-height:100px;">

2.上传成功之后获取到地址,把地址赋值给input表单里面图片的名字,另外再给img的src属性复制刚才上传的地址,在页面上吧图片读出来

    'onUploadSuccess' : function(file, data, response) {
                    $('input[name=art_thumb]').val(data);
                    $('#art_thumb_img').attr('src',data);
    //                                    alert(data);
                }

3.如果你用的是bootstrap轮播图,第一个图片要设置成class=active

  <script>
    $(function(){
        $(".item:first").addClass('active');
        //或者 $(".item").first().addClass('active');
    })
</script>

4.我自己封装了一个图片上传方法

//    上传图片
public function uploadpic( $filename, $filepath)
{
    //        1.首先检查文件是否存在
    if ($request::hasFile($filename)){
        //          2.获取文件
        $file = $request::file($filename);
        //          3.其次检查图片手否合法
        if ($file->isValid()){
//                先得到文件后缀,然后将后缀转换成小写,然后看是否在否和图片的数组内
            if(in_array( strtolower($file->extension()),['jpeg','jpg','gif','gpeg','png'])){
                //          4.将文件取一个新的名字
                $newName = 'img'.time().rand(100000, 999999).$file->getClientOriginalName();
                //           5.移动文件,并修改名字
                if($file->move($filepath,$newName)){
                    return $filepath.'/'.$newName;   //返回一个地址
                }else{
                    return 4;
                }
            }else{
                return 3;
            }
                        
        }else{
            return 2;
        }
    }else{
        return 1;
    }
}
// $realPath = $file->getRealPath(); //这个表示的是缓存在tmp文件夹下的文件的绝对路径;
// $tmpName = $file -> getFileName();   //缓存在tmp文件中的文件名
// $clientName = $file -> getClientOriginalName(); //获取文件名称
//$extension = $file->getClientOriginalExtension();   //上传文件的后缀

 //不封装,直接使用处理方法
public function store( )
{
    if ($request::hasFile('picfile')){
//          2.其次检查图片手否合法
        if ($request::file('picfile')->isValid()){
            $file = $request::file('picfile');
//                先得到文件后缀,然后将后缀转换成小写,然后看是否在否和图片的数组内
            if(in_array( strtolower($file->extension()),['pdf','txt','doc','md','html'])){
//          3.获取文件

//          4.将文件取一个新的名字
                $newName = 'join'.time().rand(100000, 999999).$file->getClientOriginalName();
//           5.移动文件,并修改名字
                $file->move('uploads/join',$newName);
                $input['card_profile'] = 'uploads/join'.'/'.$newName;
                $input['created_at'] = date('Y-m-d H:i:s');
                $res = $this->recruitment->add($input);
                if ($res){
                    return back()->with('message','简历投递成功');
                }else{
                    return back()->with('errors','简历投递失败');
                }
            }else{
                return back()->with('errors','后缀不符合');
            }

        }else{
            return back()->with('errors', '简历格式不合法');
        }
    }else{
        return back()->with('errors','没有上传简历');
    }

    }
// $realPath = $file->getRealPath(); //这个表示的是缓存在tmp文件夹下的文件的绝对路径;
// $tmpName = $file -> getFileName();   //缓存在tmp文件中的文件名
// $clientName = $file -> getClientOriginalName(); //获取文件名称
//$extension = $file->getClientOriginalExtension();   //上传文件的后缀

5.调用上传图片的方法

//    保存内容
public function store(\\Request $request )
{

    $input = Input::except('_token','picfile');
    $res = $this->uploadpic('picfile','uploads/images');
    switch ($res){
        case 1: return back()->with('errors','图片上传失败')->withInput();
        case 2: return back()->with('errors','图片不合法')->withInput();
        case 3: return back()->with('errors','图片后缀不对')->withInput();
        case 4: return back()->with('errors','图片储存失败')->withInput();
        default :
            $input['us_img'] = $res; //把得到的地址给picname存到数据库
            if($this->about->add($input)){
                return redirect('about')->with('message', '发布成功');
            }else{
                return back()->with('errors','数据填充失败')->withInput();
            }
    }
}

6.上传表单的打印

    我们来打印表单,`$request = $request::all();dd($request);`

会看到这个结果

Paste_Image.png

我们来执行

    $request = $request::all();dd($request['picfile']);
Paste_Image.png

接着,我们可以取对象里面的东西

  $request = $request::all(); //注意先先取全,得到的是数组
  $file = $request['picfile'];
  $extension = $file->extension();   //"jpeg
  $path = $file->path();   //"/private/var/tmp/phpAF4CTc"

  或者直接去file的值
  $file = $request::file('picfile');
  $extension = $file->extension();   //"jpeg
  $path = $file->path();   //"/private/var/tmp/phpAF4CTc"

另外,在其他视频中看到了一种上传图片方式

Paste_Image.png

图片拖动上传
搭建博客必备:图片拖动文本框自动上传

推荐一个上传图片的组件

github-blueimp/jQuery-File-Upload

API手册
Basic plugin

  • 使用
<!DOCTYPE HTML>
<html lang="en">
<head>
    <!-- Force latest IE rendering engine or ChromeFrame if installed -->
    <!--[if IE]>
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"><![endif]-->
    <meta charset="utf-8">
    <title>jQuery File Upload Demo - Basic version</title>
    <meta name="description"
          content="File Upload widget with multiple file selection, drag&amp;drop support and progress bar for jQuery. Supports cross-domain, chunked and resumable file uploads. Works with any server-side platform (PHP, Python, Ruby on Rails, Java, Node.js, Go etc.) that supports standard HTML form file uploads.">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- Bootstrap styles -->
    <script src="js/jquery.js"></script>
    <meta name="csrf-token" content="{{ csrf_token() }}"/>
    <link rel="stylesheet" href="css/bootstrap.min.css">

    <!-- Generic page styles -->
    <style>
        body {
            padding-top: 60px;
        }

    </style>
    <!-- CSS to style the file input field as button and adjust the Bootstrap progress bars -->
    <link rel="stylesheet" href="css/jquery.fileupload.css">
</head>
<body>

<div class="container">
    <!-- The fileinput-button span is used to style the file input field as button -->
    <span class="btn btn-success fileinput-button">
        <i class="glyphicon glyphicon-plus"></i>
        <span>请选择图片...</span>
        <!-- The file input field used as target for the file upload widget -->
        <input id="fileupload" type="file" name="files[]" multiple>
    </span>
    <br>
    <br>
    <!-- The global progress bar -->
    {{-- 上传进度条 --}}
    {{--<div id="progress" class="progress">--}}
        {{--<div class="progress-bar progress-bar-success"></div>--}}
    {{--</div>--}}
    <!-- The container for the uploaded files -->
    <div id="files" class="files"></div>
    <div class="commodity-media" id="commodity_img"></div>



</div>
<!-- The jQuery UI widget factory, can be omitted if jQuery UI is already included -->
<script src="js/vendor/jquery.ui.widget.js"></script>
<!-- The Iframe Transport is required for browsers without support for XHR file uploads -->
<script src="js/jquery.iframe-transport.js"></script>
<!-- The basic File Upload plugin -->
<script src="js/jquery.fileupload.js"></script>
<!-- Bootstrap JS is not required, but included for the responsive demo navigation -->
<script>
    /*jslint unparam: true */
    /*global window, $ */
    $(function () {
        'use strict';
        // Change this to the location of your server-side upload handler:
        $('#fileupload').fileupload({
            url: 'http://localhost/upload/upload',
            dataType: 'json',
            done: function (e, data) {
                // console.log(data.result);
                // $('<p/>').text(data.result.data.file.name).appendTo('#files');
                // if ('commodity_img' == 'commodity_img') {
                console.log(data.result.data);
                if (1) {
                    var uploadObj = data.result.data;
                    console.log(uploadObj);
                    var newImgItem = "<div class='draggable'>";

                    newImgItem += "<img src='" + uploadObj.preview_url + "' with=100/>";
                    newImgItem += '<div class="radio_btn">';
                    newImgItem += "<input type='hidden' name='upload_ids[]' value='"+uploadObj.upload_id+"'/>";
                    newImgItem += "<input type='radio' name='first_show_img' value='"+uploadObj.file_url+"'/>";
                    newImgItem += '</div>';
                    newImgItem += '<div class="radio_btn">';
                    newImgItem += '<span><a href="javascript:;" onclick="delImage(this,' +uploadObj.upload_id+ ', \'temp\')"><b>删除</b></a></span>';
                    newImgItem += '</div>';
                    $('#commodity_img').append(newImgItem);
                }

            },
            // 上传完毕进度条,但是下次上传的时候不知道怎么关闭上次的,先不开启
            // progressall: function (e, data) {
            //     var progress = parseInt(data.loaded / data.total * 100, 10);
            //     $('#progress .progress-bar').css(
            //         'width',
            //         progress + '%'
            //     );
            // }
        });
    });

</script>
</body>
</html>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,015评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,262评论 1 292
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,727评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,986评论 0 205
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,363评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,610评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,871评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,582评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,297评论 1 242
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,551评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,053评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,385评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,035评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,079评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,841评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,648评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,550评论 2 270

推荐阅读更多精彩内容

  • Bootstrap是什么? 一套易用、优雅、灵活、可扩展的前端工具集--BootStrap。GitHub上介绍 的...
    凛0_0阅读 10,689评论 3 184
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,100评论 18 139
  • 晚上十一点,宿舍还有人在挑灯看书搞疲劳战术,把被子蒙在头上怕手电筒的光影响别人休息,二十多人的宿舍里呼噜此起彼伏,...
    干货一箩筐阅读 1,304评论 0 0
  • 在中国,向来弃妇比寡妇要艰难得多。丈夫死了是值得悲怜的,被丈夫弃了却不免招来猜疑和鄙弃:“她如果没有问题,她的先生...
    罗腾树下阅读 1,050评论 1 2