您的位置:首页 > 编程语言 > Go语言

Django 实现上传图片功能

2020-03-02 01:28 751 查看

今天学习了如何使用Django实现图片上传至阿里云的功能

实现步骤

  1. 导入Webuploader

注:webuploader是一个可以上图片的模块
链接:http://fex.baidu.com/webuploader/getting-started.html

  • 在前端代码中导入 以下 JS 和 CSS
# 上传图片按钮
<div id="filePicker">选择图片</div>
#显示预览
<img width="150px" id="logoimg" src="{% static 'images/addpicture.png' %}">
# 提交时的图片地址
<input  type="hidden" id="logoplace" name="head_url" >

<script type="text/javascript" src="{% static 'webuploader/webuploader.js' %}"></script>

<link rel="stylesheet" type="text/css" href="{% static 'webuploader/webuploader.css' %}"/>

2.在JS中写入以下代码

注:server要换成对应自己视图的路由地址

<script>
// 选择文件
var uploader = WebUploader.create({
auto: true,
swf: '{% static "webuploader/Uploader.swf" %}',
server: '{% url "managebanner:uploadimg" %}',
pick: "#filePicker",
accept: {
title: "Images",
extensions: "gif,jpg,jpeg,bmp,png",
mimeTypes: "image/*"
}
});
// 文件上传成功,给item添加成功class, 用样式标记上传成功。
uploader.on( 'uploadSuccess', function( file, response ) {
console.log(111111111111111111111);
console.log(response._raw)
$('#logoimg').attr('src',response._raw)
$('#logopalce').val(response._raw)
});
</script>

3.在视图中导入csrf_exempt 模块

注:因为上传图片默认使用的是POST的方式,会被csrf_token所拦截导致后台视图报403错误 ,所以要在对应的方法名上方使用装饰器 @csrf_exempt 来跳过中间件的验证

导入该模块

from django.views.decorators.csrf import csrf_exempt
  1. 图片处理
@csrf_exempt
def uploadimg(request):
if request.method == "POST":
year = time.strftime("%Y", time.localtime(int(time.time())))
month = time.strftime("%m", time.localtime(int(time.time())))
day = time.strftime("%d", time.localtime(int(time.time())))
try:
path = "article/" + year + "/"+ month + "/" + day + "/"
f = request.FILES.get("file")
file_name = path + str(random.randint(1000000, 9999999)) + str(int(time.time()))

from urllib.request import urljoin
oss_func(fileobj=f.read(), filepath=file_name)
file_name = urljoin("http://你的仓库名.oss-cn-beijing.aliyuncs.com", file_name)
except Exception as e:
file_name = ""
print(e)
return HttpResponse(file_name)
else:
return HttpResponse('')

注:该方法中的oss_func是对应阿里云上传oss仓库的方法
代码如下

import oss2

def oss_func(fileobj, filepath):
# 阿里云主账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维,请登录 https://ram.console.aliyun.com 创建RAM账号。
auth = oss2.Auth('你的api', '你的key')
# Endpoint以杭州为例,其它Region请按实际情况填写。
bucket = oss2.Bucket(auth, 'http://oss-cn-beijing.aliyuncs.com/', '你的仓库名')
return bucket.put_object(filepath, fileobj)
  • 点赞 1
  • 收藏
  • 分享
  • 文章举报
suihsouji 发布了1 篇原创文章 · 获赞 1 · 访问量 33 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: