laravel图片和文件的上传

https://www.jianshu.com/p/51c290b56b0f

$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"


作者:栾金龙
链接:https://www.jianshu.com/p/51c290b56b0f
來源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。


猜你喜欢

转载自blog.csdn.net/weixin_39616995/article/details/80708606