获取表单传来的图片有两种方式
$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);`
会看到这个结果
我们来执行
$request = $request::all();dd($request['picfile']);
接着,我们可以取对象里面的东西
$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"
另外,在其他视频中看到了一种上传图片方式
图片拖动上传
搭建博客必备:图片拖动文本框自动上传
推荐一个上传图片的组件
github-blueimp/jQuery-File-Upload
- 使用
<!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&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>