React Native - Javascript: Download and upload PDF-files from and to Dropbox

45 Views Asked by At

In short I am trying to download and upload PDF-files from and to dropbox. Dropbox API documentation

Case 1: .txt files

For this case I have no issues when using my current sources. I am able to read the .txt file from Dropbox with the download endpoint and able to upload it again using the upload endpoint without the file getting corrupted.

Case 2: .pdf files

This is where things are going wrong and I'm hoping somebody can help me understand. I can download the PDF file without problem and save it to the disk of the android device. I have confirmed that the saved file is readable and valid with a PDF editor library. However when I then want to reupload the file to Dropbox, the file becomes unreadable and it loses a lot of content.

In this code example you can see the method I'm using to upload the .pdf file with. I store the files in base64 because the PDF editor library I am using does not work well with utf8 stored PDF files.

const SendExample = async () => {
    const fileContent = await RNFS.readFile(RNFS.CachesDirectoryPath + "/testing.pdf", 'base64');

    // console.log(atob(fileContent));

    let options = {
      method: 'POST',
      headers: {
        'Dropbox-API-Arg': JSON.stringify({ "path": `${config.dropboxOut}/testing.pdf`, "mute": true }),
        'Authorization': config.token,
        'Content-Type': 'application/octet-stream'
      },
      body: atob(fileContent)
    }

    console.log(options);

    fetch('https://content.dropboxapi.com/2/files/upload', options)
    .then(response => {
      if (!response.ok) {
        throw new Error(`File could not be uploaded! - ${JSON.stringify(response)}`);
      }
      console.log('Upload successfull');
      return response;
    })
    .catch(error => {
      // Handle any errors that occurred during the fetch
      console.error('Fetch error:', error);
    });
  };

When I compare the original and resulting PDF files I can see that in the resulting file there is a lot of content missing. It is still present on the console.log(options); log line right above the fetch request.

Please let me know if more information is required.

Thank you in advance!

0

There are 0 best solutions below