在网页上显示多个图片预览,并利用AJAX方式,向服务器提交多张图片。
由于预览是在客户端进行的,因此在提交之前,是没有流量的,不会浪费资源。
<!DOCTYPE html>
<html><head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1,user-scalable=0">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<title>上报问题</title>
<style type="text/css">
select{
border: 1px #bdbceb solid;
width: 250px;
height: 30px;
line-height: 25px;
text-indent: 2px;
border-radius: 5px;
outline: 0;
color: #000000;
padding-right: 10px;
}
.float{
float:left;
width : 110px;
height: 80px;
overflow: hidden;
border: 1px solid #CCCCCC;
border-radius: 10px;
padding: 0px;
margin: 5px;
}
img{
position: relative;
}
.result{
width: 90px;
height: 70px;
text-align: center;
box-sizing: border-box;
}
#file_input{
display: none;
}
.delete{
width: 90px;
height:70px;
position: absolute;
text-align: center;
line-height: 96px;
z-index: 10;
font-size: 30px;
background-color: rgba(255,255,255,0.8);
color: #777;
opacity: 0;
transition-duration: 0.7s;
-webkit-transition-duration: 0.7s;
}
.delete:hover{
cursor: pointer;
opacity: 1;
}
.submit {
margin-top:5px;
margin-right:10px;
display: inline-block;
width: 100px;
height:35px;
line-height:30px;
text-align:center;
background: #F60;
color: #FFF;
border:none;
}
</style>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript">
window.onload = function(){
var input = document.getElementById("file_input");
var result;
var dataArr = [];
var fd;
var oSelect = document.getElementById("select");
var oAdd = document.getElementById("add");
var oSubmit = document.getElementById("submit");
var oInput = document.getElementById("file_input");
if(typeof FileReader==='undefined'){
alert("抱歉,你的浏览器不支持 FileReader");
input.setAttribute('disabled','disabled');
}else{
input.addEventListener('change',readFile,false);
}
function readFile(){
fd = new FormData();
var iLen = this.files.length;
for(var i=0;i<iLen;i++){
if (!input['value'].match(/.jpg|.jpeg/i)){
return alert("上传的图片格式不正确,请重新选择");
}
var reader = new FileReader();
fd.append(i,this.files[i]);
reader.readAsDataURL(this.files[i]);
reader.fileName = this.files[i].name;
reader.onload = function(e){
var imgMsg = {
name : this.fileName,
base64 : this.result
}
dataArr.push(imgMsg);
result = '<div class="delete">delete</div><div class="result"><img class="subPic" src="'+this.result+'" alt="'+this.fileName+'"/></div>';
var div = document.createElement('div');
div.innerHTML = result;
div['className'] = 'float';
document.getElementsByTagName('body')[0].appendChild(div);
var img = div.getElementsByTagName('img')[0];
img.onload = function(){
var nowHeight = ReSizePic(this);
this.parentNode.style.display = 'block';
var oParent = this.parentNode;
if(nowHeight){
oParent.style.paddingTop = (oParent.offsetHeight - nowHeight)/2 + 'px';
}
}
div.onclick = function(){
$(this).remove();
}
}
}
}
function send(){
var submitArr = [];
$("#loading").html("<img src='/static/ops/img/loading.gif'/>");
$('.subPic').each(function () {
submitArr.push({
name: $(this).attr('alt'),
base64: $(this).attr('src'),
range: document.getElementById("range").value,
notes: document.getElementById("notes").value
});
}
);
$.ajax({
url : 'upload',
type : 'post',
data : JSON.stringify(submitArr),
dataType: 'json',
success : function(data){
$("#loading").empty();
if (data.result == 'OK') {
alert(data.msg);
window.location.href = "list";
}
},
error : function(data){
$("#loading").empty();
alert("提交失败");
}
})
}
oSelect.onclick=function(){
oInput.value = "";
$('.float').remove();
oInput.click();
}
oSubmit.onclick=function(){
if(!dataArr.length){
return alert('请先选择文件');
}
send();
}
}
function ReSizePic(ThisPic) {
var RePicWidth = 200;
var TrueWidth = ThisPic.width;
var TrueHeight = ThisPic.height;
if(TrueWidth>TrueHeight){
var reWidth = RePicWidth;
ThisPic.width = reWidth;
var nowHeight = TrueHeight * (reWidth/TrueWidth);
return nowHeight;
}else{
var reHeight = RePicWidth;
ThisPic.height = reHeight;
}
}
</script>
</head>
<body>
<div id="loading" style="position:absolute; top:50%;left:50%;z-index:99"></div>
<div class="container">
<label>选择或输入:</label>
<select id="ranges" onchange="document.getElementById('range').value=this.value">
<option value="">请选择</option>
<volist name="data" id="vo"><option value="{$vo.name}">{$vo.name}</option></volist> // volist是ThinkPHP的后台处理,纯网页可以更改掉
</select>
<input id="range" style="width:216px;height:20px;margin-left:-253px;margin-top:5px;border:none"/>
<div style="width:100%;height:5px"></div>
<label>内容(限255字符):</label>
<textarea style="width:98.5%;height:150px;overflow:auto;word-break: break-all;border:solid 1px #bdbceb; border-radius:5px" maxlength="255" placeholder="Blablabla……" id="notes"></textarea>
<input type="file" id="file_input" multiple accept=".jpg,.jpeg" />
<br/><button id="select" class="submit">附加图片</button>
<button id="submit" class="submit">提交</button>
<button type="button" class="submit" onclick="window.history.back(-2);">返回</button>
<div style="height:5px"></div><div>可一次性选择多张图片,点击图片可删除</div>
</div>
</body>
</html>
ThinkPHP中处理AJAX上传的多张图片的代码,在Controller中写代码:
public function upload()
{
$jsondata = json_decode(file_get_contents('php://input'));
$dir = config("upload_dir").date("Y/m/d/");
if(!file_exists($dir)) mkdir($dir, 0777, true);
$file = $jsondata[0];
$data['user']=session('user');
$data['notes']=$file->notes;
$data['range']=$file->range;
$id = Db::connect('db_config')->name('table_name1')->insertGetId($data);
foreach ( $jsondata as $file) {
$localfile = ROOT_PATH."public/".$dir.$file->name;
$thumblocalfile = ROOT_PATH."public/".$dir."s_".$file->name;
$weburl = config("webserver").$dir.$file->name;
$thumbweburl = config("webserver").$dir."s_".$file->name;
$s = str_replace("data:image/jpeg;base64,", '', $file->base64);
$s = base64_decode($s);
file_put_contents($localfile, $s);
$this->CreateThumb($localfile, $thumblocalfile);
$data2['ops_id'] = $id;
$data2['ops_pic_url'] = $weburl;
$data2['ops_pic_file'] = "public/".$dir.$file->name;
$data2['ops_pic_thumb'] = $thumbweburl;
Db::connect('db_config')->name('table_name2')->insert($data2);
}
echo '{"result": "OK", "msg": "保存成功"}';
}