python 2.7
Django 1.6.1
photoswipe
前言
对于前端的照片存储,已经在前一篇博文中进行展示,使用的是dropzone.js的包,图片存储的作用就是为了数据的再调用,所以在此片进行上次图片的前端展示,因为我是个前端萌新,所以方法比较稚嫩,希望观众老爷不要嘲笑,多多指教咯。
如何上传图片并保存请看:dropzone拖拽图片上传并保存到本地
样式的选择和调试请参考这里,非常好用---photoswipe教程事例
html
<!-- 开辟图片展示空间 -->
<div class="my-gallery" itemscope id="img_show" style="overflow-x: hidden;height:290px;"></div>
<!-- 引入js包和css样式 -->
<script type="text/javascript" src="/media/PhotoSwipe-master/dist/photoswipe.min.js"></script>
<script src="/media/PhotoSwipe-master/dist/photoswipe-ui-default.min.js"></script>
<link rel="stylesheet" href="/media/PhotoSwipe-master/dist/photoswipe.css">
<link rel="stylesheet" href="/media/PhotoSwipe-master/dist/default-skin/default-skin.css">
<!-- 官方教程中的代码 -->
<!-- Root element of PhotoSwipe. Must have class pswp. -->
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">
<!-- Background of PhotoSwipe.
It's a separate element, as animating opacity is faster than rgba(). -->
<div class="pswp__bg"></div>
<!-- Slides wrapper with overflow:hidden. -->
<div class="pswp__scroll-wrap">
<!-- Container that holds slides. PhotoSwipe keeps only 3 slides in DOM to save memory. -->
<!-- don't modify these 3 pswp__item elements, data is added later on. -->
<div class="pswp__container">
<div class="pswp__item"></div>
<div class="pswp__item"></div>
<div class="pswp__item"></div>
</div>
<!-- Default (PhotoSwipeUI_Default) interface on top of sliding area. Can be changed. -->
<div class="pswp__ui pswp__ui--hidden">
<div class="pswp__top-bar">
<!-- Controls are self-explanatory. Order can be changed. -->
<div class="pswp__counter"></div>
<button class="pswp__button pswp__button--close" title="Close (Esc)"></button>
<button class="pswp__button pswp__button--share" title="Share"></button>
<button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>
<button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>
<!-- Preloader demo http://codepen.io/dimsemenov/pen/yyBWoR -->
<!-- element will get class pswp__preloader--active when preloader is running -->
<div class="pswp__preloader">
<div class="pswp__preloader__icn">
<div class="pswp__preloader__cut">
<div class="pswp__preloader__donut"></div>
</div>
</div>
</div>
</div>
<div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
<div class="pswp__share-tooltip"></div>
</div>
<button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
</button>
<button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
</button>
<div class="pswp__caption">
<div class="pswp__caption__center"></div>
</div>
</div>
</div>
</div>
//根据官方教程,这里的style不管写在哪都可以调用,因为class名字比较独特吧
<style>
.my-gallery {
width: 100%;
float: left;
}
.my-gallery img {
width: 100%;
height: auto;
}
.my-gallery figure {
display: block;
float: left;
margin: 0 5px 5px 0;
width: 150px;
}
.my-gallery figcaption {
display: none;
}
</style>
javascript
<script>
//官方的其中一种样式
var initPhotoSwipeFromDOM = function(gallerySelector) {
// parse slide data (url, title, size ...) from DOM elements
// (children of gallerySelector)
var parseThumbnailElements = function(el) {
var thumbElements = el.childNodes,
numNodes = thumbElements.length,
items = [],
figureEl,
linkEl,
size,
item;
for(var i = 0; i < numNodes; i++) {
figureEl = thumbElements[i]; // <figure> element
// include only element nodes
if(figureEl.nodeType !== 1) {
continue;
}
linkEl = figureEl.children[0]; // <a> element
size = linkEl.getAttribute('data-size').split('x');
// create slide object
item = {
src: linkEl.getAttribute('href'),
w: parseInt(size[0], 10),
h: parseInt(size[1], 10)
};
if(figureEl.children.length > 1) {
// <figcaption> content
item.title = figureEl.children[1].innerHTML;
}
if(linkEl.children.length > 0) {
// <img> thumbnail element, retrieving thumbnail url
item.msrc = linkEl.children[0].getAttribute('src');
}
item.el = figureEl; // save link to element for getThumbBoundsFn
items.push(item);
}
return items;
};
// find nearest parent element
var closest = function closest(el, fn) {
return el && ( fn(el) ? el : closest(el.parentNode, fn) );
};
// triggers when user clicks on thumbnail
var onThumbnailsClick = function(e) {
e = e || window.event;
e.preventDefault ? e.preventDefault() : e.returnValue = false;
var eTarget = e.target || e.srcElement;
// find root element of slide
var clickedListItem = closest(eTarget, function(el) {
return (el.tagName && el.tagName.toUpperCase() === 'FIGURE');
});
if(!clickedListItem) {
return;
}
// find index of clicked item by looping through all child nodes
// alternatively, you may define index via data- attribute
var clickedGallery = clickedListItem.parentNode,
childNodes = clickedListItem.parentNode.childNodes,
numChildNodes = childNodes.length,
nodeIndex = 0,
index;
for (var i = 0; i < numChildNodes; i++) {
if(childNodes[i].nodeType !== 1) {
continue;
}
if(childNodes[i] === clickedListItem) {
index = nodeIndex;
break;
}
nodeIndex++;
}
if(index >= 0) {
// open PhotoSwipe if valid index found
openPhotoSwipe( index, clickedGallery );
}
return false;
};
// parse picture index and gallery index from URL (#&pid=1&gid=2)
var photoswipeParseHash = function() {
var hash = window.location.hash.substring(1),
params = {};
if(hash.length < 5) {
return params;
}
var vars = hash.split('&');
for (var i = 0; i < vars.length; i++) {
if(!vars[i]) {
continue;
}
var pair = vars[i].split('=');
if(pair.length < 2) {
continue;
}
params[pair[0]] = pair[1];
}
if(params.gid) {
params.gid = parseInt(params.gid, 10);
}
return params;
};
var openPhotoSwipe = function(index, galleryElement, disableAnimation, fromURL) {
var pswpElement = document.querySelectorAll('.pswp')[0],
gallery,
options,
items;
items = parseThumbnailElements(galleryElement);
// define options (if needed)
options = {
// define gallery index (for URL)
galleryUID: galleryElement.getAttribute('data-pswp-uid'),
getThumbBoundsFn: function(index) {
// See Options -> getThumbBoundsFn section of documentation for more info
var thumbnail = items[index].el.getElementsByTagName('img')[0], // find thumbnail
pageYScroll = window.pageYOffset || document.documentElement.scrollTop,
rect = thumbnail.getBoundingClientRect();
return {x:rect.left, y:rect.top + pageYScroll, w:rect.width};
}
};
// PhotoSwipe opened from URL
if(fromURL) {
if(options.galleryPIDs) {
// parse real index when custom PIDs are used
// http://photoswipe.com/documentation/faq.html#custom-pid-in-url
for(var j = 0; j < items.length; j++) {
if(items[j].pid == index) {
options.index = j;
break;
}
}
} else {
// in URL indexes start from 1
options.index = parseInt(index, 10) - 1;
}
} else {
options.index = parseInt(index, 10);
}
// exit if index not found
if( isNaN(options.index) ) {
return;
}
if(disableAnimation) {
options.showAnimationDuration = 0;
}
// Pass data to PhotoSwipe and initialize it
gallery = new PhotoSwipe( pswpElement, PhotoSwipeUI_Default, items, options);
gallery.init();
};
// loop through all gallery elements and bind events
var galleryElements = document.querySelectorAll( gallerySelector );
for(var i = 0, l = galleryElements.length; i < l; i++) {
galleryElements[i].setAttribute('data-pswp-uid', i+1);
galleryElements[i].onclick = onThumbnailsClick;
}
// Parse URL and open gallery if it contains #&pid=3&gid=1
var hashData = photoswipeParseHash();
if(hashData.pid && hashData.gid) {
openPhotoSwipe( hashData.pid , galleryElements[ hashData.gid - 1 ], true, true );
}
};
// execute above function
initPhotoSwipeFromDOM('.my-gallery');
//这里开始是自己需要写的代码,页面一开始就进行加载
window.onload=img_result();
function img_result(){
var loc = location.href;
var n1 = loc.length;//地址的总长度
var n2 = loc.indexOf("=");//取得=号的位置
var order_id = decodeURI(loc.substr(n2+1, n1-n2));//从=号后面的内容
console.log("执行了2");
//根据url写的映射,进入enter这个app然后调用get_case3这个函数进行处理
$.get('/enter/get_case3/',
{
//前台获取order_id传入后台当做参数
'order_id':order_id,
},
//从view.py中的方法可知,产生的data形式是一个list,list元素是dict,里面藏着对应dui'y'n该编号下的图片路径
function(data){
if(data[0]==""){
console.log("为空")
}
else{
var j=0
// console.log("dropzone")
var html_string='';
var aa = data.length;
console.log(aa);
for(var i=0;i<data.length;i++){
// 获取存在服务器本地文件夹中的图片路径
var newimg = '/media/'+data[i]["img"]
console.log(newimg)
html_string+='<figure itemprop="associatedMedia" style="height:200px"><a href="'+newimg+'" itemprop="contentUrl" data-size="640x1136" >![]('+newimg+')</a><figcaption itemprop="caption description"></figcaption></figure>';
j=j+1;
}
//比较弱的方法,就是构造html的字符串组,然后添加到id为img_show的空间中
$("#img_show").append(html_string);
}
},
'json' );
</script>
urls.py
这里构成的是一种前端映射到view的函数比如说,网页的后缀变成了get_case3了,映射的处理的函数指的就是后面的get_case3(完全可以写的不一样,只要找对映射关系就可以了)
urlpatterns = patterns('enter.views',
url(r"^get_case3/","get_case3"),
)
view.py
def get_case3(request):
order_id = request.GET.get("order_id","")
conn= MySQLdb.connect(
host=你的host主机,
port = 端口号,
user='root',
passwd=密码,
db =数据库名字,
)
cur = conn.cursor()
conn.set_character_set('utf8')
cur.execute('SET NAMES utf8;')
cur.execute('SET CHARACTER SET utf8;')
cur.execute('SET character_set_connection=utf8;')
# 选择出标号对应的所需要的图
cur.execute("select img from enter_img where order_id='"+order_id+"'")
server_info_advance=cur.fetchall()
advance_info2=[]
for data3 in server_info_advance:
dict_result={}
dict_result["img"]=data3[0]
advance_info2.append(dict_result)
advance_info3=[]
if len(advance_info2)<100: #
return advance_info2
else:
return advance_info3
model的表现形式
# 数据库名字叫做enter_img
+-----+----------+-------------------------------------+
| id | order_id | img |
+-----+----------+-------------------------------------+
| 460 | 1234 | upload/1491036872.27WechatIMG2.png |
+-----+----------+-------------------------------------+
这里回顾下过程,整个流程在于在前端触发一个带返回的id号,之后将这个id号代入后台进行数据库的索引,之后再从后台构造好传递到前端,前端在进行图片展示,photoswipe这个js包的作用就是完成图片比较酷炫展示的作用,其中要注意的是图片尺寸的选择,后续有空需要把自动获取尺寸的代码构造出来,目前如果不是非本分辨率的图片,放大后将呈现出很差的体验效果,后续可能会对图片上传时,对图片尺寸的进行获取和存值,这样再进行调出的时候,效果就会好很多。--来自自学前端三个礼拜的小白的心声
Pay Attention
- 关于id的传入,这里用的方法非常的朴素,应该是从一个页面点击该id然后获取该id下的明细,也就是涉及到页面跳转的概念了,然后再将id传递进入后台,再操作
最后
关于为啥我把上传图片和展示图片分成两篇来写,,,,,因为,,我懒啊,哈哈哈哈,不闹,片段剥离,有利于重复利用,嗯,就是酱紫
后续
解决问题毕竟还是需要进行复盘和记录,这样对以后的发展和回顾有非常大的益处,构造方法上的选择需要接轨目前主要的方法,对于前后台脱离的团队,需要进行标准的数据传输,前端妹子们可不管后台怎么构造方法,她们只要进行前端页面展示就可以了(然而ui,美工,后台都tm是我写0.0),后续等我有空闲下来的时间,把整个构建构建工程和app的过程都仔细写一下,从整个项目中剥离出来让纯正小白也可以一下子学会,目前只能当为自己的学习笔记,如果思想对你有所帮助,我也很高兴。共勉
网友评论