示例#1
0
 def upload(self, path, filedata):
     # qcloud_cos needs path to startswith /
     if not path.startswith("/"):
         path = "/" + path
     if isinstance(filedata, text_type):
         req = qcloud_cos.UploadFileRequest(self.bucket,
                                            path,
                                            filedata,
                                            insert_only=0)
         return self._cos_client.update_file(req)
     elif isinstance(filedata, binary_type):
         req = qcloud_cos.UploadFileFromBufferRequest(self.bucket,
                                                      path,
                                                      filedata,
                                                      insert_only=0)
         return self._cos_client.upload_file_from_buffer(req)
     else:
         raise TypeError(
             "filedata should be filename(text_type) or content(binary_type)"
         )
示例#2
0
    def upload(self, bucket, path, local_file):
        """
        上传本地文件到 COS, 将覆盖已经存在的文件

        :param bucket: bucket name
        :param path: dest cos path
        :param local_file: local file
        """
        req = qcos.UploadFileRequest(unicode(bucket),
                                     unicode(path),
                                     unicode(local_file),
                                     insert_only=0)
        resp = self.client.upload_file(req)
        if resp["code"] != 0:
            # COS 上传失败的文件会保留, 下次上传时无法覆盖, 这里先删除
            if resp["message"].find("status_code:403") != -1:
                req = qcos.DelFileRequest(unicode(bucket), unicode(path))
                self.client.del_file(req)

            raise Exception(resp["message"])
示例#3
0
region_info = "gz"  #           # 替换为用户的region,目前可以为 sh/gz/tj,分别对应于上海,广州,天津园区
cos_client = qcloud_cos.CosClient(appid,
                                  secret_id,
                                  secret_key,
                                  region=region_info)

# 设置要操作的bucket
bucket = u'zhangh214'

############################################################################
# 文件操作                                                                 #
############################################################################
# 1. 上传文件(默认不覆盖)
#    将本地的py_demo.py上传到bucket的根分区下,并命名为py_demo.py
#    默认不覆盖, 如果cos上文件存在,则会返回错误
request = qcloud_cos.UploadFileRequest(bucket, u'/demokit.py', u'py_demo2.py')
upload_file_ret = cos_client.upload_file(request)
print 'upload file ret:', repr(upload_file_ret)

# 2. 上传文件(覆盖文件)
#    将本地的py_demo2.py上传到bucket的根分区下,覆盖已上传的py_demo.py
request = qcloud_cos.UploadFileRequest(bucket, u'/demokit.py', u'py_demo2.py')
request.set_insert_only(0)  # 设置允许覆盖
upload_file_ret = cos_client.upload_file(request)
print 'overwrite file ret:', repr(upload_file_ret)

# 3. 获取文件属性
request = qcloud_cos.StatFileRequest(bucket, u'/demokit.py')
stat_file_ret = cos_client.stat_file(request)
print 'stat file ret:', repr(stat_file_ret)
示例#4
0
def loadDataToCos(filein,fileout):
    request = qcloud_cos.UploadFileRequest(bucketname, fileout, filein, u'bizAttribute')
    upload_file_ret = cos_client.upload_file(request)
    print "upload file retresult : ", upload_file_ret
示例#5
0
def creatSection(request):
    try:
        body = request.POST.dict()
        if 'courseid' not in body:
            t = loader.get_template('upload.html')
            return HttpResponse(t.render())
        user = tokenActive({'token': body['token']})
        if not isinstance(user, User):
            return pack(code=user)
        # 如果是学生,那么不让创建
        if user.type == 0:
            return pack(msg='学生无法创建课程')
        # 获取当前时间戳
        now = int(1000 * time.time())
        id = random_str()
        section = EditSection(sectionid=id,
                              creattime=now,
                              creator=user.userid,
                              type=body['type'],
                              title=body['title'],
                              father=body['courseid'],
                              operator=0)
        # 获取上传的文件,如果没有文件,则默认为None
        file = request.FILES.get("file", None)
        if not file:
            pack(msg="no files for upload!")

        # 文字文件和视频文件分别处理
        if body['type'] == '1':
            appid = 1252409052
            secret_id = u'AKIDQkspaAxYEZItIV7K2axCF6yuhHIDfVr0'
            secret_key = u'CG8nkZJtJXaS7au1vdJsGtOp4JQQFsRp'
            region_info = u"tj"
            cos_client = qcloud_cos.CosClient(appid,
                                              secret_id,
                                              secret_key,
                                              region=region_info)
            creatSectionFile(file=file, section=section)
            request = qcloud_cos.UploadFileRequest(
                u'conlinestatic1', u'/sectionfile/' + section.fileurl,
                u'' + sectionfiledir + section.fileurl)
            res = cos_client.upload_file(request)
            if res['code'] != 0:
                raise Exception('上传失败')
            request = qcloud_cos.UpdateFileRequest(
                u'conlinestatic1', u'/sectionfile/' + section.fileurl)
            request.set_content_disposition(u'inline; filename=' +
                                            section.fileurl)
            cos_client.update_file(request)
            os.remove(sectionfiledir + section.fileurl)
        elif body['type'] == '0':
            filetype = '.' + str(file).split('.')[1]
            # 如果是txt或者md那么存到数据库
            if filetype == '.txt' or filetype == '.md':
                filecontent = file.read()
                # 获取编码方式
                encodetype = chardet.detect(filecontent)['encoding']
                section.content = filecontent.decode(encodetype)
            # 如果是pdf那么创建文件
            elif filetype == '.pdf':
                creatSectionFile(file=file, section=section)
            # 如果是doc那么先转pdf再保存文件
            elif filetype == '.doc':
                creatSectionFile(file=file, section=section)
                desfile = random_str() + '.pdf'
                log('des: ' + desfile)
                log('sre' + section.fileurl)
                office = subprocess.Popen(['sh', '/home/ubuntu/office.sh'])
                office.wait()
                write = subprocess.Popen([
                    'python3', '/home/ubuntu/DocumentConverter.py',
                    sectionfiledir + section.fileurl, sectionfiledir + desfile
                ],
                                         stderr=subprocess.PIPE,
                                         stdout=subprocess.PIPE)
                write.wait()
                if write.stderr.read() != '':
                    log('error: ' + write.stderr.read())
                    raise Exception('上传出错')
                section.fileurl = desfile
            else:
                raise Exception('文件类型错误')
        section.save()

        return pack()
    except Exception as e:
        return pack(msg=e)
示例#6
0
文件: qcloud_cos.py 项目: F-xxx/Fxx
def upload_file(des,loc):
    request = qcloud_cos.UploadFileRequest(bucketname, des, loc, u'bizAttribute')
    upload_file_ret = cos_client.upload_file(request)
    print "upload file retresult : ", upload_file_ret