• django使用七牛云上传图片或文件


    首先要在python 中安装qiniu

    使用 pycharm可以很方便的安装,打开project interpreter,然后搜索即可

    coding: utf-8

    from django.shortcuts import redirect, render, HttpResponse
    import json
    import os
    import uuid
    from blog import models
    import qiniu
    import logging

    七牛云上传图片配置

    access_key = 'xxxx'
    secret_key = 'xxxx'
    bucket_name = 'store1' #填你的bucket名
    remote_url_prefix = 'xxxx' # 用于拼接img网址

    def upload(reqeust):
    '''
    将文件进行上传
    :param reqeust:
    :return: 返回wang editor所要求的数据
    '''
    image = reqeust.FILES.get('image', None)
    img_url = qiniu_upload(image)
    print(img_url)

    result = {"errno": 0, 'data': [img_url, ]}  # 给wang editor返回的参数
    return HttpResponse(json.dumps(result))
    

    def qiniu_upload(file):
    """
    使用七牛云
    :param file:
    :return:
    """
    binary_file = file.read()
    q = qiniu.Auth(access_key, secret_key)
    token = q.upload_token(bucket=bucket_name, )

    result, response_info = qiniu.put_data(token, None, binary_file)
    image_remote_url = remote_url_prefix+'/'+result.get('hash') # 使用返回值拼接网址得到img网址
    return image_remote_url
    

    再附上普通的写法(通过IO写入本地文件):

    def normal_upload(image):
    """
    普通方式上传,写入本地文件
    :param image: 从request获取的image
    :return:
    """
    cwd = os.getcwd()
    myuuid = str(uuid.uuid1()).replace('-', '')
    new_filename = myuuid + image.name
    relative_path = os.path.join(r'blogupload', new_filename)
    file_upload_url = os.path.join(cwd, relative_path)
    logging.info(f'上传了图片,位置:{file_upload_url}')
    # os.makedirs(file_upload_url)
    with open(file_upload_url, mode="wb+") as f: # 将文件写入blog下的upload文件夹
    for chunk in image.chunks():
    f.write(chunk)
    img_url = "http://localhost:8000/static/" + new_filename # upload配置了static,也需要用static访问

  • 相关阅读:
    工作中遇到新知识应该怎么办
    Java中的集合
    JSTL学习(二)自定义标签库
    别跟我扯依赖注入
    经典算法的分析
    Debian
    C 底层细节【转】
    C文件操作 【转】
    利用strstr和sscanf解析GPS信息
    算法学习建议 ACM()转
  • 原文地址:https://www.cnblogs.com/li-xiao-yang/p/13951999.html
Copyright © 2020-2023  润新知