在django中使用七牛雲


一、配置環境

django 3.0.3 

qiniu 7.2.6

全部可以使用pip安裝

二、在app的目錄下創建qiniu_config.py文件,用於存放七牛雲的相關配置信息

qiniu_config = {
    'access_key': '',
    'secret_key': '',
    'bucket_name': '',
    'domine': '',
}
#bucket_name:空間名
#domine:cdn加速域名

三、views.py

from django.shortcuts import render, HttpResponse
import qiniu
import json
from qiniu_app.qiniu_config import qiniu_config


# 七牛身份驗證
def qiniu_auth():
    access_key = qiniu_config['access_key']
    secret_key = qiniu_config['secret_key']
    q = qiniu.Auth(access_key, secret_key)
    return q


# Create your views here.
# 將上傳處理后的圖片刷新到cdn節點,減少回源流量
def cdn_flush(key):
    auth = qiniu_auth()
    cdn_manager = qiniu.CdnManager(auth)
    domine = qiniu_config['domine']
    need_flush_url = domine + key
    # 需要刷新的文件鏈接
    urls = [
        need_flush_url,
    ]
    # URL刷新鏈接
    refresh_url_result = cdn_manager.refresh_urls(urls)
    return


# 進行上傳的圖片處理
def dealwith_img(request):
    q = qiniu_auth()
    key = request.GET.get('key')
    bucket_name = qiniu_config['bucket_name']
    # pipeline是使用的隊列名稱,不設置代表不使用私有隊列,使用公有隊列。
    # pipeline = 'your_pipeline'
    # 要進行的轉換格式操作。
    fops = 'imageView2/0/format/webp/interlace/1'
    # 可以對縮略后的文件進行使用saveas參數自定義命名,當然也可以不指定文件會默認命名並保存在當前空間
    saveas_key = qiniu.urlsafe_base64_encode(bucket_name + ':' + key)
    fops = fops + '|saveas/' + saveas_key
    # pfop = qiniu.PersistentFop(q, bucket_name, pipeline)
    pfop = qiniu.PersistentFop(q, bucket_name)
    ops = []
    ops.append(fops)
    ret, info = pfop.execute(key, ops, 1)
    assert ret['persistentId'] is not None
    cdn_flush(key)
    return HttpResponse(json.dumps('ok'))


# 獲取七牛上傳的token
def qntoken(request):
    q = qiniu_auth()
    key = request.GET.get('key')
    bucket = qiniu_config['bucket_name']
    token = q.upload_token(bucket, key)
    return HttpResponse(json.dumps({'token': token}))


def qiniu_test(request):
    return render(request, 'qiniu_test.html')

四、urls.py

from django.urls import path
from qiniu_app import views
urlpatterns = [
    path('qntoken/', views.qntoken, name="qntoken"),
    path('', views.qiniu_test, name="qiniu_test"),
    path('dealwith_img/', views.dealwith_img, name="dealwith_img"),
]

五、html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
    <script src="https://unpkg.com/qiniu-js@2.5.5/dist/qiniu.min.js"></script>
</head>
<body>


<from>
    <input type="file" id="img" value="上傳圖片">
</from>
上傳后的url:<span id="img_url"></span>


<script>// 上傳完圖片后做的事情
    function com_img(ret) {
        var img_name = ret['key'];
        var domine = ''; // cdn加速域名
        var img_url = domine + img_name; //合成訪問的鏈接
        $('span#img_url').text(img_url);
        // 在后端處理上傳的圖片
        $.ajax({
            url: '{% url 'dealwith_img' %}',
            type: 'GET',
            data: {'key': img_name},
            dataType: 'json',
            error: function () {
                alert("處理失敗")
            }
        })
    }

    $('#img').change(function () {
            var token = '';
            var file_img = $('#img').get(0).files[0];
            var key = (new Date()).getTime() + '.' + file_img.name.split('.')[1];
            $.ajax({
                url: '{% url 'qntoken' %}',
                type: 'GET',
                data: {'key': key},
                dataType: 'json',
                success: function (token_msg) {
                    token = token_msg['token'];
                    console.log(token);
                    var putExtra = {
                        fname: key,
                        params: {},
                        mimeType: ['image/png', 'image/jpeg']
                    };
                    var config = {
                        useCdnDomain: true,
                        retryCount: 6,
                        region: qiniu.region.z0
                    };
                    var observable = qiniu.upload(file_img, key, token, putExtra, config)
                    var subscription = observable.subscribe({'error': up_err, 'complete': com_img}) // 上傳開始
                }
            });
        }
    );

</script>
</body>
</html>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM