【问题标题】:Replace existing file on upload上传时替换现有文件
【发布时间】:2021-05-18 11:19:19
【问题描述】:

我正在尝试使用以下代码将文件上传到框中的文件夹:

folder_id = '22222'
new_file = client.folder(folder_id).upload('/home/me/document.pdf')
print('File "{0}" uploaded to Box with file ID {1}'.format(new_file.name, new_file.id))

此代码不会替换 box 文件夹中现有的 document.pdf,而是保留文件的旧版本。我想删除目标中的文件并保留最新文件。如何做到这一点?

【问题讨论】:

    标签: python boxsdk


    【解决方案1】:

    由于您的目标是替换原始文件,因此您可以尝试覆盖其现有内容。 Here is an example. 你需要检查文件名是否已经存在于 BOX 文件夹中

    folder_id = '22222'
    file_path = '/home/me/document.pdf'
    
    results = client.search().query(query='document', limit=1, ancestor_folder_ids=[folder_id], type='file', file_extensions=['pdf'])    
    file_id = None
    for item in results:
        file_id = item.id
    
    if file_id:
        updated_file = client.file(file_id).update_contents(file_path)
        print('File "{0}" has been updated'.format(updated_file.name))
    else:
        new_file = client.folder(folder_id).upload(file_path)
        print('File "{0}" uploaded to Box with file ID {1}'.format(new_file.name, new_file.id))
    

    【讨论】:

    • 如何获取结果文件?
    • @TomJMuthirenthi,请查看更新后的答案
    【解决方案2】:

    它不会替换它,因为每次您上传新文件时,它都会为其分配一个新 id,因此旧文件永远不会被替换。 这是我在官方文档中找到的。 试着给它起个名字,然后试试。

    upload[source]
    Upload a file to the folder. The contents are taken from the given file path, and it will have the given name. If file_name is not specified, the uploaded file will take its name from file_path.
    
    Parameters: 
    file_path (unicode) – The file path of the file to upload to Box.
    file_name (unicode) – The name to give the file on Box. If None, then use the leaf name of file_path
    preflight_check (bool) – If specified, preflight check will be performed before actually uploading the file.
    preflight_expected_size (int) – The size of the file to be uploaded in bytes, which is used for preflight check. The default value is ‘0’, which means the file size is unknown.
    upload_using_accelerator (bool) –
    If specified, the upload will try to use Box Accelerator to speed up the uploads for big files. It will make an extra API call before the actual upload to get the Accelerator upload url, and then make a POST request to that url instead of the default Box upload url. It falls back to normal upload endpoint, if cannot get the Accelerator upload url.
    
    Please notice that this is a premium feature, which might not be available to your app.
    
    Returns:    
    The newly uploaded file.
    
    Return type:    
    File
    

    【讨论】:

    • 我怎样才能使文件的替换工作?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-30
    • 1970-01-01
    • 2012-10-26
    • 1970-01-01
    • 2021-10-11
    • 1970-01-01
    • 2011-12-24
    相关资源
    最近更新 更多