上传时替换现有文件

Replace existing file on upload

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

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,而是保留文件的旧版本。我想删除目标中的文件并保留最新文件。如何实现?

它不会替换它,因为每次您上传新文件时,它都会为其分配一个新的 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

由于您的目标是替换原始文件,您可以尝试覆盖其现有内容。 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))