1

I am trying to upload a file in to a folder in the box using the below code:

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))

This code is not replacing the existing document.pdf in the box folder, rather it is keeping the older version of the file. I would like to remove the file in the target and keep the latest file. How to achieve this?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Tom J Muthirenthi
  • 3,028
  • 7
  • 40
  • 60

2 Answers2

2

Since your goal is to replace the original file, you can try to overwrite its existing content. Here is an example. You will need to check for the filename if it is already present in the BOX folder though

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))
Tom J Muthirenthi
  • 3,028
  • 7
  • 40
  • 60
Sandeep Gusain
  • 127
  • 1
  • 1
  • 10
1

Its not replacing it because every time you upload new file it assign it a new id so the old file will never be replaced. This is what I found in official docs. Try to give it a name and then try that.

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
SaGaR
  • 534
  • 4
  • 11