python --上传图片到oss

简单上传

def Uploadoss(path, names):
	:params
	:path 文件相对路径
	 : names 文件后缀	
    auth = oss2.Auth('key', '秘钥')
    bucket = oss2.Bucket(auth, 'http://oss-cn-beijing.aliyuncs.com', 'oss根路径')
    name = f'topic/{uuid.uuid4()}{names}'  # 要上传的路径
    bucket.put_object_from_file(上传oss全路径, 本地文件全路径)
    image_url = 'https://indeximage.oss-cn-beijing.aliyuncs.com/' + name  # oss外网访问绝对路径
    return image_url

分片上传

def upload_img(ext, file):
    '''
    oss分片上传
    :param ext [文件后缀]
    :param file [本地文件路径]
    :return oss文件访问路径
    '''
    auth = oss2.Auth('LTAI5tJ2sSKPh8LQBMkvYr9d', '863CjuhKeGAEvL4lZTXpNdlHo0JfMN')
    bucket = oss2.Bucket(auth, 'http://oss-cn-chengdu.aliyuncs.com', 'oss2videos')

    key = str(time.time()) + str(ext)
    filename = file

    total_size = os.path.getsize(filename)
    part_size = determine_part_size(total_size, preferred_size=100 * 1024)
    upload_id = bucket.init_multipart_upload(key).upload_id
    parts = []

    # 逐个上传分片。
    with open(filename, 'rb') as fileobj:
        part_number = 1
        offset = 0
        while offset < total_size:
            num_to_upload = min(part_size, total_size - offset)
            result = bucket.upload_part(key, upload_id, part_number,
                                        SizedFileAdapter(fileobj, num_to_upload))
            parts.append(PartInfo(part_number, result.etag))

            offset += num_to_upload
            part_number += 1

    bucket.complete_multipart_upload(key, upload_id, parts)
    oss_file = r'https://oss2videos.oss-cn-chengdu.aliyuncs.com/{}'.format(key)
    return oss_file

配合djagno

@api_view(['POST', ])
def upload_files(request: HttpRequest) -> HttpResponse:
    '''
    上传一切文件资源,接口后台通用
    :param {参数名: files, 类型: files, 是否必选: 必选, 说明: 一切文件资源}
    :return 文件路径
    '''
    t = time.strftime('%Y%m%d%H%M%S')
    img = request.FILES.get('files')
    if img.size <= 2621440 * 39:
        ext = os.path.splitext(img.name)[1]  # 后缀
        img_name = str(t) + ext
        with open(f'{MEDIA_ROOT}/{img_name}', 'ab') as f:
            for chunk in img.chunks():
                f.write(chunk)

        oss_path = upload_img(ext, f'{MEDIA_ROOT}/{img_name}')
        print(oss_path)

        hint = {
            'code': 0,
            'message': '上传成功!',
            # 'url': f'{MEDIA_URL}{img_name}',
            'oss_path': oss_path
        }
    else:
        hint = {'code': 500, 'message': '文件不能大于100M!'}
    return Response(hint)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

像风一样的男人@

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值