Search code examples
javascriptgoogle-drive-api

Issue with Copying and Pasting Files Using Google Drive API


I'm encountering an issue when trying to use the Google Drive API to copy and paste a file into a specific folder. The copy operation is successful; however, the copied file is pasted back into the source folder instead of being moved to the specified destination folder.

Here is the code snippet I'm using:

// File ID you want to copy.
const folderId = '1g9rSD-file_copied';

// New folder ID that will be the destination of the copy.
const parentFolderId = '1xu6TIz_my_folder_destination';       
const accessToken = "my_access_token_here";

const requestBody = {
    parents: [parentFolderId],
    supportsAllDrives: true,
};

const queryString = new URLSearchParams(requestBody).toString();
const copyUrl = `https://www.googleapis.com/drive/v3/files/${folderId}/copy?${queryString}`;

fetch(copyUrl, {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${accessToken}`,
    }
})
.then(response => response.json())
.then(data => {

    console.log('Cópia concluída:', data);
})
.catch(error => {
    console.error('Erro na requisição:', error);
});

I expected the file to be copied to the folder specified in parentFolderId, but instead, it's pasted into the source folder.

Has anyone faced a similar issue or has any suggestions on what might be causing this unexpected behavior?

Appreciate any help in advance!


Solution

  • I believe your goal is as follows.

    • You want to copy a file costs.xls in the folder model_files to the folder model_files.
    • You want to achieve this using the fetch API of Javascript.
    • Your access token is a valid token for copying the file using Drive API.

    In this case, how about the following modification?

    Modified script:

    Before you run this script, please set fileId, destinationFolderId, and accessToken.

    // Please set the file ID of the file "costs.xls".
    const fileId = '###';
    
    // Please set the folder ID of the folder "model_files".
    const destinationFolderId = '###';
    
    // Please set your access token.
    const accessToken = "###";
    
    
    const queryParameters = { supportsAllDrives: true };
    const queryString = new URLSearchParams(queryParameters).toString();
    const copyUrl = `https://www.googleapis.com/drive/v3/files/${fileId}/copy?${queryString}`;
    
    fetch(copyUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${accessToken}`,
      },
      body: JSON.stringify({ parents: [destinationFolderId] })
    })
      .then(response => response.json())
      .then(data => {
    
        console.log('Cópia concluída:', data);
      })
      .catch(error => {
        console.error('Erro na requisição:', error);
      });
    
    • When this script is run, the file of fileId is copied to the folder of destinationFolderId.

    • At Google Drive, the files and folders are managed by the unique IDs. So, when the file ID is known, the file can be directly retrieved even when the parent folder ID of the file is not known.

    Reference: