原文链接
微信公众号开发,图片处理部分
上篇文章已经获取了wx的接口权限
本来想直接使用wx的图像接口,但是后来发现处理js动作有点小麻烦
还有些莫名的错误,就选择了好用的weui.js
挺好用~
(为了少走弯路,建议直接用weui.js)
首先我们设置后端代码接收前端post,在上篇文章已经提到
# Image字段
class Image(models.Model):
file = models.ImageField('图片', upload_to=image_filename, blank=True)
name = models.CharField('文件名', blank=True, null=True, max_length=256)
uploaded_by = models.ForeignKey(FansProfile, verbose_name='上传者', on_delete=models.CASCADE)
created_time = models.DateTimeField('创建时间', auto_now_add=True)
last_modify_time = models.DateTimeField('最后修改时间', auto_now=True)
class activity(View):
def post(self,request,*args, **kwargs):
request_type = request.POST.get('type')
if not request_type:
pass # 处理ticket获取
elif request_type == 'image/jpeg':
files = request.FILES.getlist('fileVal')[0]
filename = request.POST.dict()['name']
uploader_id = request.COOKIES.get('fanid','')
check_id = FansProfile.objects.filter(id=uploader_id).first()
if not check_id:
return HttpResponseRedirect(web_get_code+'snsapi_base#wechat_redirect')
post_image = Image(file = files) # Image数据库模型
post_image.uploaded_by = check_id
post_image.name = filename.split('.')[:-1][0]
post_image.save()
return HttpResponse(json.dumps({'statue':True}),content_type="application/json")
然后来到前端,下面是简单的实现
就是weui.js文档和演示html的堆砌
详情点击weui.js-docs
weui.js预览
{% load static %}
<script>
$(document).ready(function () {
var uploadCountDom = document.getElementById("uploadCount")
var url = location.href.split('#')[0];
var uploadCount = 0,
uploadList = [];
$('#uploaderInput').on("click", function (e) {
weui.uploader('#uploader', {
url: url,
auto: false,
type: 'file',
fileVal: 'fileVal',
compress: {
width: 1600,
height: 1600,
quality: .8
},
onBeforeQueued: function (files) {
// `this` 是轮询到的文件, `files` 是所有文件
if (["image/jpg", "image/jpeg", "image/png", "image/gif"].indexOf(this.type) < 0) {
weui.alert('请上传图片');
return false; // 阻止文件添加
}
if (this.size > 10 * 1024 * 1024) {
weui.alert('请上传不超过10M的图片');
return false;
}
if (files.length > 5) { // 防止一下子选择过多文件
weui.alert('最多只能上传5张图片,请重新选择');
return false;
}
if (uploadCount + 1 > 5) {
weui.alert('最多只能上传5张图片');
return false;
}
++uploadCount;
uploadCountDom.innerHTML = uploadCount
// return true; // 阻止默认行为,不插入预览图的框架
},
onQueued: function () {
uploadList.push(this);
console.log(this);
// console.log(this.status); // 文件的状态:'ready', 'progress', 'success', 'fail'
// console.log(this.base64); // 如果是base64上传,file.base64可以获得文件的base64
// this.upload(); // 如果是手动上传,这里可以通过调用upload来实现;也可以用它来实现重传。
// this.stop(); // 中断上传
// return true; // 阻止默认行为,不显示预览图的图像
},
onBeforeSend: function (data, headers) {
console.log(this, data, headers);
// $.extend(data, { test: 1 }); // 可以扩展此对象来控制上传参数
$.extend(headers, { 'X-CSRFToken': '{{ csrf_token }}' }); // 可以扩展此对象来控制上传头部
// return false; // 阻止文件上传
},
onProgress: function (procent) {
console.log(this, procent);
// return true; // 阻止默认行为,不使用默认的进度显示
},
onSuccess: function (ret) {
console.log(this, ret);
// return true; // 阻止默认行为,不使用默认的成功态
},
onError: function (err) {
console.log(this, err);
// return true; // 阻止默认行为,不使用默认的失败态
}
});
})
// 缩略图预览
document.querySelector('#uploaderFiles').addEventListener('click', function (e) {
var target = e.target;
while (!target.classList.contains('weui-uploader__file') && target) {
target = target.parentNode;
}
if (!target) return;
var url = target.getAttribute('style') || '';
var id = target.getAttribute('data-id');
if (url) {
url = url.match(/url\((.*?)\)/)[1].replace(/"/g, '');
}
var gallery = weui.gallery(url, {
className: 'custom-name',
onDelete: function onDelete() {
weui.confirm('确定删除该图片?', function () {
--uploadCount;
uploadCountDom.innerHTML = uploadCount;
for (var i = 0, len = uploadList.length; i < len; ++i) {
var file = uploadList[i];
if (file.id == id) {
file.stop();
break;
}
}
target.remove();
gallery.hide();
});
}
});
});
document.querySelector('#images-del').addEventListener('click', function () {
options.onDelete.call(this, url);
});
document.querySelector('#confirmBtn').addEventListener('click', function () {
weui.confirm('确定提交吗?', function () {
uploadList.forEach(function (file) {
file.upload();
});
console.log('yes');
}, function () {
console.log('no');
}, {
title: '提交确认'
});
});
});
</script>
<div class="weui-gallery">
<span class="weui-gallery__img"></span>
<div class="weui-gallery__opr">
<a href="javascript:" class="weui-gallery__del">
<i class="weui-icon-delete weui-icon_gallery-delete" id="images-del"></i>
</a>
</div>
</div>
<div class="weui-cells weui-cells_form" id="uploader">
<div class="weui-cell">
<div class="weui-cell__bd">
<div class="weui-uploader">
<div class="weui-uploader__hd">
<p class="weui-uploader__title">图片上传</p>
<div class="weui-uploader__info">
<span id="uploadCount">0</span>/5</div>
</div>
<div class="weui-uploader__bd">
<ul class="weui-uploader__files" id="uploaderFiles"></ul>
<div class="weui-uploader__input-box">
<input id="uploaderInput" class="weui-uploader__input" type="file" accept="image/*" capture="camera" multiple="" />
</div>
</div>
</div>
</div>
</div>
</div>
<div class="weui-btn-area">
<a class="weui-btn weui-btn_primary" href="javascript:" id="confirmBtn">确定</a>
</div>
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。