Python的两种上传图片方式

Python的两种上传图片方式

1.上传至七牛云服务器

2.上传至自己服务器

1.上传至七牛云服务器

access_key = '替换成你的'
# 个人中心->密匙管理->SK
secret_key = '替换成你的'
# 七牛空间名
bucket_name = '替换成你的'
#临时域名
url = '替换成你的'
q = qiniu.Auth(access_key, secret_key)


def qiniu_upload(key, localfile):
 
    token = q.upload_token(bucket_name, key, 3600)
    ret, info = qiniu.put_file(token, key, localfile)
    if ret:
        return 'http://{0}/{1}'.format(url, ret['key'])
    else:
        raise Exception('上传失败,请重试')

@csrf_exempt
def upload_qiniu(request):
    """
              @api {POST} /upload_qiniu/ [上传图片至七牛]
               * @apiVersion 0.0.1
               * @apiGroup upload
              @apiParamExample {params} 请求参数
                  "image":""       "图片文件"
              @apiSuccessExample {json} 成功返回
                      {
                "message": "",
                "next": "",
                "data": "",
                "response": "ok",
                "error": ""
            }
              @apiSuccessExample {json} 失败返回
              {
                  "message": "",
                  "next": "",
                  "data": null,
                  "response": "fail",
                  "error": "上传失败","缺少参数"
              }
              """
    image = request.FILES.get("image")
    if not image:
        return ajax.jsonp_fail(request, u"缺少参数")
    service_name = save_block_file(image)
    data=qiniu_upload(service_name,get_absolute_file_path(service_name))
    if data:
        return ajax.jsonp_ok(request, data)
    else:
        return ajax.jsonp_fail(request, u"上传失败")

def save_upload_file(new_file_path, raw_file,name):
    """
    功能说明:保存上传文件
    raw_file:原始文件对象
    new_file_path:新文件绝对路径
    """
    try:
        # 如果新文件存在则删除
        if os.path.exists(new_file_path):
            try:
                os.remove(new_file_path)
            except:
                pass

        content = raw_file.read()
        fp = open(new_file_path, 'wb')
        fp.write(content)
        fp.close()
        return name
    except Exception as e:
        print (e)
        return False


def save_block_file(block_file):
    """
    :param block_file: 文件对象
    :return:
    """
    # 唯一标识 + 文件名   201801171.png
    now_time = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
    name = '%s%s' % (now_time, block_file.name)
    block_file_path = get_absolute_file_path(name).replace("\\", "/")
    # 文件上传保存
    return save_upload_file(block_file_path, block_file, name)


def get_absolute_file_path(file_name):
    """
    功能说明:返回绝对路径字符串
    file_name:文件名字
    """
    media_root = settings.UPLOAD
    print ("media_root",media_root)
    absolute_file_path = os.path.join(media_root, file_name)
    print("absolute_file_path", absolute_file_path)
    # 返回文件绝对路径中目录路径
    file_dir = os.path.dirname(absolute_file_path)
    print ("file_dir", file_dir)
    if not os.path.exists(file_dir):
        # 创建路径
        os.makedirs(file_dir)
    return absolute_file_path

上传至自己服务器

@csrf_exempt
def insert_img(request):
    """
              @api {POST} /upload/ [上传图片]
               * @apiVersion 0.0.1
               * @apiGroup note
              @apiParamExample {params} 请求参数
                  "image":""       "图片文件"
          
              """
    image = request.FILES.get("image")
    if not image:
        return ajax.jsonp_fail(request, u"缺少参数")
    service_name = save_block_file(image)
    path = '%s/%s' % ("你的服务器地址", service_name)
    if not path:
        return ajax.jsonp_fail(request, u"上传失败")
    else:
        return ajax.jsonp_ok(request, path)


def save_upload_file(new_file_path, raw_file,name):
    """
    功能说明:保存上传文件
    raw_file:原始文件对象
    new_file_path:新文件绝对路径
    """
    try:
        # 如果新文件存在则删除
        if os.path.exists(new_file_path):
            try:
                os.remove(new_file_path)
            except:
                pass

        content = raw_file.read()
        fp = open(new_file_path, 'wb')
        fp.write(content)
        fp.close()
        return name
    except Exception as e:
        print(e)
        return False


def save_block_file(block_file):
    """
    :param block_file: 文件对象
    :return:
    """
    # 唯一标识 + 文件名   201801171.png
    now_time = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
    name = '%s%s' % (now_time, block_file.name)
    block_file_path = get_absolute_file_path(name).replace("\\", "/")
    # 文件上传保存
    return save_upload_file(block_file_path, block_file,name)


def get_absolute_file_path(file_name):
    """
    功能说明:返回绝对路径字符串
    file_name:文件名字

    """
    media_root = settings.UPLOAD
    print("media_root",media_root)
    absolute_file_path = os.path.join(media_root, file_name)
    print("absolute_file_path", absolute_file_path)
    # 返回文件绝对路径中目录路径
    file_dir = os.path.dirname(absolute_file_path)
    print("file_dir", file_dir)
    if not os.path.exists(file_dir):
        # 创建路径
        os.makedirs(file_dir)
    return absolute_file_path
发布了60 篇原创文章 · 获赞 6 · 访问量 7986

猜你喜欢

转载自blog.csdn.net/qq_43030934/article/details/103984937