如何使用Microsoft Graph覆盖上传到SharePoint的文件

时间:2018-07-27 17:00:49

标签: python sharepoint microsoft-graph onedrive

我有一个Python脚本,它将使用Microsoft Graph将文件上传到Sharepoint,但是当我尝试两次上传同一文件时,它给我一个500状态码错误。

以下是上传文件的函数的代码:

def upload_file(session,filename,driveid,folder):

    """Upload a file to Sharepoint.

    """
    fname_only = os.path.basename(filename)

    # create the Graph endpoint to be used

    endpoint = f'drives/{driveid}/root:/{folder}/{fname_only}:/createUploadSession'

    start_response = session.put(api_endpoint(endpoint))
    json_response = start_response.json()
    upload_url = json_response["uploadUrl"]

# upload in chunks

    filesize = os.path.getsize(filename)

    with open(filename, 'rb') as fhandle:
        start_byte = 0
        while True:
            file_content = fhandle.read(10*1024*1024)
            data_length = len(file_content)
            if data_length <= 0:
                break

            end_byte = start_byte + data_length - 1
            crange = "bytes "+str(start_byte)+"-"+str(end_byte)+"/"+str(filesize)
            print(crange)
            chunk_response = session.put(upload_url,
                                         headers={"Content-Length": str(data_length),"Content-Range": crange},
                                         data=file_content)
            if not chunk_response.ok:
                print(f'<Response [{chunk_response.status_code}]>')
                pprint.pprint(chunk_response.json()) # show error message
                break

            start_byte = end_byte + 1

    return chunk_response

这是第一次运行的输出:

bytes 0-10485759/102815295
bytes 10485760-20971519/102815295
bytes 20971520-31457279/102815295
bytes 31457280-41943039/102815295
bytes 41943040-52428799/102815295
bytes 52428800-62914559/102815295
bytes 62914560-73400319/102815295
bytes 73400320-83886079/102815295
bytes 83886080-94371839/102815295
bytes 94371840-102815294/102815295

这是第二次运行的输出:

bytes 0-10485759/102815295
bytes 10485760-20971519/102815295
bytes 20971520-31457279/102815295
bytes 31457280-41943039/102815295
bytes 41943040-52428799/102815295
bytes 52428800-62914559/102815295
bytes 62914560-73400319/102815295
bytes 73400320-83886079/102815295
bytes 83886080-94371839/102815295
bytes 94371840-102815294/102815295
<Response [500]>
{'error': {'code': 'generalException',
           'message': 'An unspecified error has occurred.'}}

我想我可以在覆盖文件之前弄清楚如何删除文件,但是由于Sharepoint保留版本,因此保留历史记录会很不错。

谢谢您的帮助。

鲍比

p.s。我一直在破解https://github.com/microsoftgraph/python-sample-console-app中的代码,以获取将文件上传到SharePoint的功能,因此该功能中的某些代码来自Microsoft的示例应用程序。

1 个答案:

答案 0 :(得分:1)

根据下面的Microsoft文章,对于任何在此期间遇到文件名冲突问题的人,如果文件名冲突并且您没有正确指定应替换它,则最后的字节范围上传将失败OP描述的方式。希望这对某人有帮助。

  

处理上传错误

     

上载文件的最后一个字节范围时,可能会发生错误。这可能是由于名称冲突或配额限制被超出。上传会话将一直保留到到期时间,这样您的应用就可以通过明确提交上传会话来恢复上传。

发件人:https://docs.microsoft.com/en-us/onedrive/developer/rest-api/api/driveitem_createuploadsession?view=odsp-graph-online#create-an-upload-session