Reputation: 31
I'm trying to use v3 of the Drive API to copy a file. Although I'm successful in getting a copy of the file to be created, neither the copied file's title nor location is changed as I had hoped. Looking at code snippets available online, I'm not sure what's wrong with my code, so any help would be greatly appreciated.
def copy(service, file_id, dest_id): #Drive service, id of file to be copied, id of destination folder
service.files().copy(
fileId=file_id,
supportsAllDrives=True,
body = {
'title':'copiedFile',
'parents' : [ {'kind':"drive#fileLink",
'id': dest_id}],
}
).execute()
Upvotes: 1
Views: 2723
Reputation: 271
For anyone else coming to this in 2024 using the Google Drive v3 API, the answer is to use the 'name' parameter instead of 'title':
function copyFile(fileId, parentId, newFileName) {
const copiedFile = Drive.Files.copy({
name: newFileName,
parents: [{
id: parentId,
}]
}, fileId, {
supportsAllDrives: true
});
return copiedFile.id;
}
Upvotes: 0
Reputation: 31
Managed to figure this out own by own, it turned out to be a fairly simple approach - here's the code for a function that handles copying a single file.
#Handles copying of a file.
#If no new destination (parent) is provided, it is copied
#into the same location the original file was located.
def copy(service, fileID, parents=None):
mimetype = service.files().get(fileId=fileID, fields='mimeType', supportsAllDrives=True).execute()['mimeType']
if mimetype == 'application/vnd.google-apps.folder': #If the provided file id points to a folder
#Code to handle copying a folder
else:
file_metadata = {}
if parents is not None: #If custom destination is specified, add it to the file metadata
file_metadata['parents'] = [parents]
#Copy the file
file = service.files().copy(
fileId=fileID,
body=file_metadata,
fields='id, name', #Can be whatever fields you want, I just like having access to the resulting file id & name
supportsAllDrives=True).execute()
Upvotes: 2
Reputation: 685
You need to copy the file first, then update it by first removing the current parents and then adding the ID of the new parent folder. Here's a snippet that should do the trick:
copy = (
service.files()
.copy(
fileId=file_id,
body={"title": "copiedFile"},
)
.execute()
)
service.files().update(
fileId=copy.get("id"),
addParents=dest_id,
removeParents=copy.get("parents"),
fields="id, parents",
).execute()
Upvotes: 1