Django上传图片到七牛云

七牛云存储

介绍:

七牛云存储是一个集图片、视频对象存储为一体的网站。并且他上面集成了cdn加速服务,图片处理(加水印,图片裁剪)等功能,对于一些想要快速开发产品,不想花大量时间来构建自己资源服务器的中小型公司而言,无疑是最好的选择。

准备工作:

  1. 到七牛官网:https://www.qiniu.com/。创建账号。然后到个人面板->秘钥管理处获取access_keysecret_key。 
  2. 创建空间,可以选择华东区,华南区等。 

使用:

后端:

1. 下载Python SDK:

通过命令pip install qiniu即可下载七牛的SDK

2. 创建一个获取tokenurl

​
# views.py
import qiniu

@require_GET
def qntoken(request):
    access_key = '你的access_key'
    secret_key = '你的secret_key'
    q = qiniu.Auth(access_key, secret_key)

    bucket = 'xtspace'  # 七牛云的存储空间名
    token = q.upload_token(bucket)
    return restful.result(kwargs={"uptoken":token})

​

然后在urls.py中做一个url与视图函数的映射。示例代码如下:

​
from django.urls import path
urlpatterns = [
    path('qntoken/',views.qntoken,name='qntoken')
]

​

前端:

  1. 在模板中引入最新版(2.4.0)的JavaScript SDK

    
    
  2. 然后监听一个type=file类型的按钮的change事件,一旦选择了文件,那么就会执行change事件,在change事件的处理函数中,我们就可以获取到当前选中的文件。然后通过七牛的SDK发送给服务器。示例代码如下:

​
​
 function News() {
     var self = this;
     self.progressGroup = $("#progress-group");
     self.progressBar = $(".progress-bar");
 }

 News.prototype.listenQiniuUploadFileEvent = function () {
     var self = this;
     var thumbnailBtn = $('#thumbnail-btn');
     thumbnailBtn.change(function (event) {
         var file = this.files[0];
         xfzajax.get({
             'url': '/cms/qntoken/',
             'success': function (result) {
                 var token = result['uptoken'];
                 var key = (new Date()).getTime() + '.' + file.name.split('.')[1];
                 var putExtra = {
                     fname: key,
                     params: {},
                     mimeType: ['image/png','video/x-ms-wmv','image/jpeg']
                 };
                 var config = {
                     useCdnDomain: true,
                     retryCount: 6,
                     region: qiniu.region.z2
                 };
                 var observable = qiniu.upload(file, key, token, putExtra,config);
                 observable.subscribe({
                     "next":self.updateUploadProgress,
                     "error":self.uploadErrorEvent,
                     "complete": self.complateUploadEvent
                 });
                 self.progressGroup.show();
             }
         });
     });
 };

 News.prototype.updateUploadProgress = function (response) {
     var self = this;
     var total = response.total;
     var percent = total.percent;
     var percentText = percent.toFixed(0) + '%';
     var progressBar = $(".progress-bar");
     progressBar.css({"width":percentText});
     progressBar.text(percentText);
 };

 News.prototype.uploadErrorEvent = function (error) {
     window.messageBox.showError(error.message);
 };

 News.prototype.complateUploadEvent = function (response) {
     var self = this;
     var filename = response['key'];
     var domain = "http://og209xb9x.bkt.clouddn.com/";
     var thumbnailUrl = domain + filename;
     var thumbnailInput = $("#thumbnail-form");
     thumbnailInput.val(thumbnailUrl);
     var progressGroup = $("#progress-group");
     progressGroup.hide();
 };

​
​

-----------------------------------------------------------------------------------------------------------------

文中用到的js和result类

xfzajax.js

/**
 * Created by hynev on 2018/5/15.
 */

function getCookie(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = jQuery.trim(cookies[i]);
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

var xfzajax = {
    'get': function (args) {
        args['method'] = 'get';
        this.ajax(args);
    },
    'post': function (args) {
        args['method'] = 'post';
        this._ajaxSetup();
        this.ajax(args);
    },
    'ajax': function (args) {
        var success = args['success'];
        args['success'] = function (result) {
            if(result['code'] === 200){
                if(success){
                    success(result);
                }
            }else{
                var messageObject = result['message'];
                if(typeof messageObject == 'string' || messageObject.constructor == String){
                    window.messageBox.showError(messageObject);
                }else{
                    // {"password":['密码最大长度不能超过20为!','xxx'],"telephone":['xx','x']}
                    for(var key in messageObject){
                        var messages = messageObject[key];
                        var message = messages[0];
                        window.messageBox.showError(message);
                    }
                }
                if(success){
                    success(result);
                }
            }
        };
        args['fail'] = function (error) {
            console.log(error);
            window.messageBox.showError('服务器内部错误!');
        };
        $.ajax(args);
    },
    '_ajaxSetup': function () {
        $.ajaxSetup({
            beforeSend: function(xhr, settings) {
                if (!/^(GET|HEAD|OPTIONS|TRACE)$/.test(settings.type) && !this.crossDomain) {
                    xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
                }
            }
        });
    }
};

result.py

from django.http import JsonResponse


class HttpCode(object):
    """docstring for HttpCode"""
    ok = 200
    paramserror = 400
    unauth = 401
    methoderror = 405
    servererror = 500


def result(code=HttpCode.ok, message='', data=None, kwargs=None):
    json_dict = {'code': code, 'message': message, 'data': data}

    if kwargs and isinstance(kwargs, dict) and kwargs.keys():
        json_dict.update(kwargs)

    return JsonResponse(json_dict)


def ok():
    return result()


def params_error(message='', data=None):
    return result(code=HttpCode.paramserror, message=message, data=data)


def unauth(message='', data=None):
    return result(code=HttpCode.unauth, message=message, data=data)


def method_error(message='', data=None):
    return result(code=HttpCode.methoderror, message=message, data=data)


def server_error(message='', data=None):
    return result(code=HttpCode.servererror, message=message, data=data)

 

 

相关链接:

  1. 七牛官网:https://www.qiniu.com/
  2. Python SDK地址:https://developer.qiniu.com/kodo/sdk/1242/python
  3. JavaScript SDK地址:https://developer.qiniu.com/kodo/sdk/1283/javascript

你可能感兴趣的:(Django)