python django 上传文件到七牛

# -*- coding:utf-8 -*-
import json
import uuid
import os
from qiniu import Auth, put_data
from django.http import HttpResponse


class UploadFilesToQiNiu(object):

    def post(self, request):

        try:
            cur_file = request.FILES.get('file', '')
        except:
            return HttpResponse(json.dumps({"message": "No File Uploaded"}), status=400,
                                content_type="application/json")
        # 生成name
        cur_file_name = cur_file.name
        file_name_list = cur_file_name.split('.')
        file_last_name = file_name_list[-1]
        cur_file_name = str(uuid.uuid4()) + '.' + file_last_name

        # 上传需要二进制流格式
        my_file = open(cur_file_name, 'wb')
        my_file.write(cur_file.read())
        my_file.close()
        my_file = open(cur_file_name, 'rb')

        upload_to_qiniu(cur_file_name,
                        my_file,
                        settings.QINIU_BUCKET_NAME)

        #
        cur_link = 'http://' + settings.QINIU_DOMAIN + '/' + cur_file_name
        my_file.close()
        os.remove(cur_file_name)
        return HttpResponse(json.dumps({"filelink": cur_link}), content_type="application/json")


def upload_to_qiniu(key, localfile, bucket_name):
    '''
    key: 上传到七牛后保存的文件名
    localfile: 要上传文件的本地路径或者文件
    bucket_name: 要上传的空间
    '''
    # Access Key  Secret Key
    access_key = 'kkkkkk'
    secret_key = 'kkkkkk'

    # 构建鉴权对象
    q = Auth(access_key, secret_key)

    # 生成上传 Token,可以指定过期时间等
    token = q.upload_token(bucket_name, key, 3600)

    ret, info = put_data(token, key, localfile)
    # print ret
    # print info
    return ret, info

  

posted @ 2018-02-01 16:57  django_start  阅读(267)  评论(0编辑  收藏  举报