效果图
HTML
<table class="layui-table" style="margin-top: 30px;">
<thead>
<tr>
<th style="width: 100px;">文件</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<div class="forms" style="width: 100px;">
//保存图片的地址
<input type="hidden" name="voucher_url[]" class="voucher_url">
//保存图片的名称
<input type="hidden" name="voucher_name[]" value="WechatIMG513.png" required="" class="voucher_name">
<input type="file" name="file" class="voucher">
//显示图片名称
<span class="voucher_span">文件上传</span>
</div>
</td>
</tr>
<tr>
<td>
<div class="forms" style="width: 100px;">
//保存图片的地址
<input type="hidden" name="voucher_url[]" class="voucher_url">
//保存图片的名称
<input type="hidden" name="voucher_name[]" value="WechatIMG513.png" required="" class="voucher_name">
<input type="file" name="file" class="voucher">
//显示图片名称
<span class="voucher_span">文件上传</span>
</div>
</td>
</tr>
<tr>
<td>
<div class="forms" style="width: 100px;">
//保存图片的地址
<input type="hidden" name="voucher_url[]" class="voucher_url">
//保存图片的名称
<input type="hidden" name="voucher_name[]" value="WechatIMG513.png" required="" class="voucher_name">
<input type="file" name="file" class="voucher">
//显示图片名称
<span class="voucher_span">文件上传</span>
</div>
</td>
</tr>
</tbody>
</table>
JS
layui.use(['laydate', 'laypage', 'layer', 'table', 'carousel', 'upload', 'element','form'], function(){
var laydate = layui.laydate //日期
,laypage = layui.laypage //分页
,layer = layui.layer //弹层
,table = layui.table //表格
,form = layui.form
,upload = layui.upload
,element = layui.element; //元素操作
//上传文件的图片
uploadFun = function(obj){
upload.render({
elem: obj
,url: '/index/production/uploadattache'//上传的接口
,done: function(res, index, upload){ //上传后的回调
if(res.status==200){
$(obj).prev().prev().val(res['data'][1]);
$(obj).prev().val(res['data']['source_name']);
$(obj).next().html(res['data']['source_name']);
}else{
layer.msg(res.msg, {icon:2});
}
}
,accept: 'file' //允许上传的文件类型
});
}
//为需要上传的元素绑定上传函数
$.each($('.voucher'),function(i,item){
uploadFun(item);
});
});
PHP
//上传接口
public function uploadattache(){
$file = request()->file('file');
$fileinfo = $file->getInfo();
$path = 'public'.DS.'uploads'.DS.'file'.DS.Date('Ym',time());
$info = $file->move(ROOT_PATH . $path,rand().time().strrchr($fileinfo['name'], '.') );
$res['source_name'] = $fileinfo['name'];
$back = '/public/uploads'.DS.'file'.DS.Date('Ym',time());
if(!$info){
return json(array('status'=>'500','data'=>'','msg'=>$this->error($file->getError())));
}
return json(array('status'=>'200','data'=>[true,'source_name'=>$fileinfo['name'],$back.'/'.$info->getSaveName()],'msg'=>''));
}
以上代码可以直接使用,js动态增加元素,也可以使用这种方法。