问题
I created a script that can upload files on Google Drive Shared Drives using service account. However, I having trouble on renaming the file. I always get "Untitled" file name.
This is my code:
function movefiletoDrive(fileId, driveID, parentDriveId){
var body = {"title":"RJ"}
var service = getDriveService();
service.reset()
if (service.hasAccess()) {
var url = 'https://www.googleapis.com/drive/v3/files/'+fileId+'?addParents='+driveID+'&removeParents='+parentDriveId+'&supportsTeamDrives=true';
var params = {
headers: {
Authorization: 'Bearer ' + service.getAccessToken()
},
method:'PATCH'
};
var response2 = UrlFetchApp.fetch(url, params);
var response2parse = JSON.parse(response2.getContentText());
var newFileId = response2parse.id
//changeFileName(newFileId);
Logger.log(response2parse);
}
}
I've tried add the parameter "title" and "name" on the URL to change the file name but no luck.
Any help will be appreciated. Thanks.
回答1:
- It is crucial to define the
contentType
- The correct parameter for the UL fetch is
name
, nottitle
A working code could look like this:
function movefiletoDrive(fileId, driveID, parentDriveId){
var body = {"name":"RJ"}
var service = getDriveService();
service.reset()
if (service.hasAccess()) {
var url = 'https://www.googleapis.com/drive/v3/files/'+fileId+'?addParents='+driveID+'&removeParents='+parentDriveId+'&supportsTeamDrives=true';
var params = {
headers: {
Authorization: 'Bearer ' + service.getAccessToken()
},
method:'patch',
contentType: 'application/json',
payload: JSON.stringify(body)
};
var response2 = UrlFetchApp.fetch(url, params);
var response2parse = JSON.parse(response2.getContentText());
var newFileId = response2parse.id;
changeFileName(newFileId);
Logger.log(response2parse);
}
}
If you encounter any issue with this solution or the one I provided for your other question - please be so kind to come back to me about this.
来源:https://stackoverflow.com/questions/61797113/change-file-name-of-file-uploaded-using-google-drive-api-apps-script