项目中需要一次上传多个图片,看了一些插件,如jquery-file-upload,Dropzone JS,它们在选中图片后就立马上传了,没有给用户check的机会(可能是我没学到精华~_~),有点不适合,所以没用,后面网上看到了个别人的思路(忘了在哪个博客上看的):点击一次就生成一个 input type=file 并触发;
然后就自己写了
1.点击一次就生成一个 input type=file 并触发;
2.选中后将缩略图显示在<div id="img11">
3.点击缩略图用模态框显示大图
4.点击确定按钮上传到服务器(后端用的Django)
效果图:
下面是代码
HTML代码:
<div>
//图片选择按钮
<div class="input-group item1" οnclick="seleclt_file()">
<span class="input-group-addon title1">圖片<span style="color: #00b3ee">(最多選擇5張)</span></span>
</div>
<div id="fileDiv1" style="display: none">
<form action="" id="upload_form"></form>
</div>
//图片展示div
<div id="img11" style="width: 400px;height: 80px;"></div>
</div>
<div style="margin-top: 0; width:400px;">
<button class="btn btn-default" style="float:right">确定</button>
</div>
</div>
//模态框,用于图片预览
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog mymodal">
<div class="modal-content">
<div class="modal-body" style="padding: 0">
<img id="show_pic1" src="" alt="" width="600px" height="600px">
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal -->
</div>
JS代码:
var this_width,this_height;
$(document).ready(function () {
this_width = document.body.clientWidth;
this_height = document.body.clientHeight;
del_img_input();
preview();
});
function submit() {
var form = document.getElementById('upload_form');
var formData = new FormData(form);
$.ajax({
url: "/Do_records/",
type: "POST",
data: formData,
processData: false,
contentType: false,
success:function(data){
if(data['status'] === 1) {
swal({
title: '異常記錄',
text: data['message'],
type: 'success'
});
$('input[name="files"]').remove();
$('div[name="img_div"]').remove();
}
else{
swal({
title: '異常記錄',
text: data['message'],
type: 'error'
});
}
},
error:function(err){
alert("网络连接失败,稍后重试" + err);
}
});
}
// 文件选择,最多选择5张图片
function seleclt_file() {
var result_input_file = del_blank_input_file();
if(result_input_file === 0){
return
}
try{ $("#show_img_div").removeAttr("id");}
catch(err){}
try{ $("#uploaderInput").removeAttr("id");}
catch(err){}
uploadFile = '<input name="files" id="uploaderInput" type="file" accept="image/*" οnchange=""/>';
$("#upload_form").append($(uploadFile));
$("#uploaderInput").click();
$("#uploaderInput").bind("change", function (e) {
// 可以做一些其他的事,比如图片预览
addr =document.getElementById('uploaderInput').value;
// 添加div
show_img_div = '<div id="show_img_div" name="img_div" class="' + addr +'"style="float:left;width:60;height:60px;margin-right: 10px"></div>';
$('#img11').append(show_img_div);
// 添加<img>标签
show_img = '<img src="" width="60" height="60px" name="img"><br>';
$('#show_img_div').append(show_img);
// 添加删除选项
del_img = '<button οnclick="" class="del" style="width: 60px;text-align:center;color: white; font-size: 8px;background-color: #3c5277;border: 0px">刪除</button>';
$('#show_img_div').append(del_img);
reads = new FileReader();
f = document.getElementById('uploaderInput').files[0];
var namelist = document.getElementsByName('files');
reads.readAsDataURL(f);
reads.οnlοad=function (e) {
$('#show_img_div img').attr('src',this.result);
};
$("#uploaderInput").removeAttr("id");
});
}
// 选中文件删除
function del(addr) {
var namelist = document.getElementsByName('files');
var img_divlist = document.getElementsByName('img_div');
for(var i=0;i<namelist.length;i++){
if(namelist[i].value===addr){
namelist[i].remove();
}
}
for(var j=0;j<img_divlist.length;j++){
if(img_divlist[j].className===addr){
img_divlist[j].remove();
}
}
}
function del_blank_input_file() {
var namelist = document.getElementsByName('files');
if(namelist.length > 4){
swal({
title: '圖片選擇',
text: '您已選擇了5張圖片,無法繼續選擇!\n請刪除後再選',
type: 'error'
});
return 0
}
for(var i=0;i<namelist.length;i++){
if(namelist[i].value === ''){
namelist[i].remove();
}
}
return 1
}
function del_img_input() {
$('#img11').on('click', 'div button.del' ,function () {
var g = $(this).closest('div').attr('class');
del(g);
});
}
// 选中文件預覽
function preview() {
var namelist = document.getElementsByName('files');
$('#img11').on('click', 'div img' ,function () {
var classname = $(this).closest('div').attr('class');
for(var i=0;i<namelist.length;i++){
if(namelist[i].value === classname){
reads = new FileReader();
f = namelist[i].files[0];
reads.readAsDataURL(f);
reads.οnlοad=function (e) {
var image = new Image();
image.src = this.result;
image.onload = function () {
var width = image.width;
var height = image.height;
if (width < this_width - 50 && height < this_height - 50){
$('#show_pic1').attr({'width': width,'height': height});
$('.modal-dialog').css({'width' : width});
}
else{
$('#show_pic1').attr({'width': '600px','height': '600px'});
$('.modal-dialog').css({'width' : '600px'});
}
};
$('#myModal').modal();
$('#show_pic1').attr('src',this.result);
};
}
}
});
}
后端Django代码:
@api_view(['POST'])
def Do_records(request):
context = {}
if request.method == 'POST':
try:
org_path = "D:\\Anomaly_Records\\static\\upload_img"
time_strp = time.strftime('%Y_%m_%d',time.localtime(time.time()))
org_path = os.path.join(org_path, time_strp)
make_dirs(org_path)
a = request.POST
myFile_list = request.FILES.getlist('files', None) # input 标签中的name值
if not myFile_list:
path_str = ''
else:
k=0
path_str = ''
filename_list = []
for myFile in myFile_list:
if myFile.name in filename_list:
context['status'] = 0
context['message'] = "選中兩個命名相同的文件,請確認!-->" + myFile.name
return response(context)
final_path = os.path.join(org_path, myFile.name)
filename_list.append(myFile.name)
if os.path.exists(final_path):
context['status'] = 0
context['message'] = "系统已存在相同命名的文件!-->" + myFile.name
return response(context)
for myFile in myFile_list:
final_path = os.path.join(org_path, myFile.name)
destination = open(final_path, 'wb+') # 打开特定的文件进行二进制的写操作
for chunk in myFile.chunks(): # 分块写入文件
destination.write(chunk)
destination.close()
final_path = final_path.replace('\\','\\\\\\\\') # D:\\Anomaly_Records\\EnVew\\static\\upload_img\\2019_05_29\\123.jpg
final_path = final_path[21:]
path_str = path_str + final_path + ";"
command = "INSERT into anomaly_records(Station,Line,Fail_item,Stop_time,Fail_time,Reason_result,Work_num,Department,Work_name,Pic) " \
"VALUES('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')" \
%(a['Station'],a['Line'],a['Fail_item'],a['Stop_time'],a['Fail_time'],a['Reason_result'],a['Work_num'],a['Department'],a['Work_name'],path_str)
result = my_insert_Test(command)
if result == 1:
context['status'] = 1
context['message'] = '記錄OK'
elif result == 0:
context['status'] = 0
context['message'] = '插入數據庫失敗'
else:
context['status'] = 0
context['message'] = '插入多筆記錄,請通知管理員修正'
context['status'] = 1
except Exception as e:
context['status'] = 0
context['message'] = str(e)
write_error(str(e))
finally:
return response(context)