Upload Files using the Multipart Post Method with Google Script
This code snippet shows how you can use the use the multipart post method to upload a file from Google Drive to Box using the Box API and Google Script. The PDF file is already on Google Drive, it gets the blob of the file using the File_ID and uploads to a specific Box folder (FOLDER_ID).
// Written by Amit Agarwal www.labnol.org
function uploadFile() {
var boundary = 'labnol';
var blob = DriveApp.getFileById(GOOGLE_DRIVE_FILE_ID).getBlob();
var attributes = '{"name":"abc.pdf", "parent":{"id":"FOLDER_ID"}}';
var requestBody = Utilities.newBlob(
'--' +
boundary +
'\r\n' +
'Content-Disposition: form-data; name="attributes"\r\n\r\n' +
attributes +
'\r\n' +
'--' +
boundary +
'\r\n' +
'Content-Disposition: form-data; name="file"; filename="' +
blob.getName() +
'"\r\n' +
'Content-Type: ' +
blob.getContentType() +
'\r\n\r\n'
)
.getBytes()
.concat(blob.getBytes())
.concat(Utilities.newBlob('\r\n--' + boundary + '--\r\n').getBytes());
var options = {
method: 'post',
contentType: 'multipart/form-data; boundary=' + boundary,
payload: requestBody,
muteHttpExceptions: true,
headers: { Authorization: 'Bearer ' + getBoxService_().getAccessToken() },
};
var request = UrlFetchApp.fetch('https://upload.box.com/api/2.0/files/content', options);
Logger.log(request.getContentText());
}
Unlike Google Drive that allows multiple files of the same name, Box is more restrictive. It rejects files that have names longer than 255 characters or duplicate files with the same name.
The HTTP multipart request is commonly used to upload files and other data over to a HTTP Server. A “multipart/form-data” message contains a series of parts separated by boundaries. Each part should contain the “Content-Disposition” header whose value is “form-data” and if a file is being sent to the server, the contentType should also be included.
If the same request is made with curl, the request will be:
curl https://upload.box.com/api/2.0/files/content \\
-H "Authorization: Bearer ACCESS_TOKEN" -X POST \\
-F attributes='{"name":"file.pdf", "parent":{"id":"FOLDER_ID"}}' \\
-F file=@file.pdf
Amit Agarwal
Google Developer Expert, Google Cloud Champion
Amit Agarwal is a Google Developer Expert in Google Workspace and Google Apps Script. He holds an engineering degree in Computer Science (I.I.T.) and is the first professional blogger in India.
Amit has developed several popular Google add-ons including Mail Merge for Gmail and Document Studio. Read more on Lifehacker and YourStory