Upload to Dropbox
Upload files to specified directory in Dropbox. You can specify whether to overwrite files with the same name.
Configs for this Auto Step
- conf_OAuth2
- C1: OAuth2 Setting *
- conf_Directory
- C2: Directory on Dropbox (e.g. “/aaa/bbb/”) *#{EL}
- conf_uploadedFile
- C3: FILE DATA for Upload *
- conf_isOverWrite
- C4: is overwrite the existing file
- conf_fileId
- C5: STRING DATA for file ids (update)
- conf_fileUrl
- C6: STRING DATA for file urls (update)
Script (click to open)
// Upload to Dropbox via DropboxAPI v2 (ver. 202307)
// OAuth2 config sample at [OAuth 2.0 Setting]
// - Authorization Endpoint URL: https://www.dropbox.com/oauth2/authorize?token_access_type=offline
// - Token Endpoint URL: https://api.dropboxapi.com/oauth2/token
// - Scope:
// - Consumer Key: (Get by Dropbox)
// - Consumer Secret: (Get by Dropbox)
const SIZE_LIMIT = 94371840; //File size border of Questetra (90MB)
main();
function main(){
//// == 工程コンフィグの参照 / Config Retrieving ==
const oauth2 = configs.get( "conf_OAuth2" ) + "";
const directory = configs.get( "conf_Directory" ) + "";
const isOverWrite = configs.getObject( "conf_isOverWrite" );
const idDataDef = configs.getObject("conf_fileId");
const urlDataDef = configs.getObject("conf_fileUrl");
//// == ワークフローデータの参照 / Data Retrieving ==
const files = engine.findData(configs.getObject("conf_uploadedFile"));
if (files === null) {
engine.log("no file");
return;
}
//// == 演算 / Calculating ==
checkDirectory(directory)
checkFile(files, idDataDef, urlDataDef);
let uploadedFileData = [[], []]; //0:ID,1:URL
for (let i = 0; i < files.size(); i++) {
engine.log("upload filename:" + files.get(i).getName());
upload(oauth2, files.get(i), directory, uploadedFileData, isOverWrite);
}
//// == ワークフローデータへの代入 / Data Updating ==
setData(idDataDef, uploadedFileData[0]);
setData(urlDataDef, uploadedFileData[1]);
}
/**
* アップロード先のディレクトリ名のチェック
* @param {String} directory アップロード先ディレクトリ名
*/
function checkDirectory(directory) {
//ディレクトリのチェック、スラッシュ始まり・スラッシュ終わりかどうか
const regex = /^\/.*\/$/;
if (!(regex.test(directory))) {
throw "Invalid directory";
}
}
/**
* アップロードしようとするファイルの数・サイズが適切かどうかチェック
* @param {Array<File>} files アップロードしようとするファイルの配列
* @param {ProcessDataDefinitionView} idDataDef ID を保存するデータ項目の ProcessDataDefinitionView
* @param {ProcessDataDefinitionView} urlDataDef URL を保存するデータ項目の ProcessDataDefinitionView
*/
function checkFile(files, idDataDef, urlDataDef) {
const fileNum = files.size(); //number of files
if (fileNum > httpClient.getRequestingLimit()) {
throw "Number of requests is over the limit";
}
//1つでもファイルサイズオーバーあったら中止
files.forEach(file => {
engine.log(`Uploading: ${file.getName()}`);
if (file.getLength() > SIZE_LIMIT) {
throw "There is a file over the size limit";
}
});
checkfileNum(idDataDef, fileNum);
checkfileNum(urlDataDef, fileNum);
}
/**
* アップロードするファイルが複数で パス・URL 出力先のデータ項目が単一行ならエラーにする
* @param {ProcessDataDefinitionView} dataDef データ項目の ProcessDataDefinitionView
* @param {Number} fileNum アップロードしようとするファイルの個数
*/
function checkfileNum(dataDef, fileNum) {
if (dataDef !== null) {
//Multiple Judge
if (dataDef.matchDataType("STRING_TEXTFIELD") && fileNum > 1) {
throw "Multiple files are set though the Data Item to save the output is Single-line String."
}
}
}
/**
* ファイルをアップロードする。一回につき一つのみ。
* @param {String} oauth2 OAuth2 設定
* @param {File} file アップロードするファイル
* @param {String} directory アップロード先ディレクトリ名
* @param {Array<Array<String>>} uploadedFileData アップロードしたファイルの情報を格納する二次元配列
* @param {Boolean} isOverWrite 同名ファイルを上書きするか
*/
function upload(oauth2, file, directory, uploadedFileData, isOverWrite) {
const uri = "https://content.dropboxapi.com/2/files/upload";
let json;
if ( isOverWrite ) {
json = '{"path": "' + directory + escaper.escapeJson(file.getName()) + '", "mode": "overwrite"}';
} else {
json = '{"path": "' + directory + escaper.escapeJson(file.getName()) + '"}';
}
//engine.log("json:"+json);
let response = httpClient.begin()
.authSetting( oauth2 )
.header( "Dropbox-API-Arg", json )
.body( file, "application/octet-stream" )
.post( uri );
engine.log("---POST request--- " + response.getStatusCode());
const responseString = response.getResponseAsString();
engine.log(responseString);
const status = response.getStatusCode();
if( status >= 300 ){
engine.log("Failed to upload status:" + status);
throw `Failed to upload\nstatus: ${status}\nfile: ${file.getName()}`;
}
engine.log("upload successful");
addOutputToArray(responseString, uploadedFileData);
}
/**
* アップロードしたデータのIDとURLを配列にセットする。
* @param {String} responseStr 送信時のレスポンスをテキスト出力したもの
* @param {Array<String>} uploadedFileData アップロードしたファイルの情報が格納される配列
*/
function addOutputToArray(responseStr, uploadedFileData) {
const json = JSON.parse(responseStr);
uploadedFileData[0].push(json.id);
uploadedFileData[1].push(`https://www.dropbox.com/home${json.path_display}`);
}
/**
* アップロードしたデータのパスとURLをデータ項目に出力する。
* @param {ProcessDataDefinitionView} dataDef データ項目の ProcessDataDefinitionView
* @param {Array<String>} uploadedFileData アップロードしたファイルの情報が格納されている配列
*/
function setData(dataDef, uploadedFileData) {
if (dataDef !== null) {
engine.setData(dataDef, uploadedFileData.join('\n'));
}
}
Download
- Dropbox-upload-202307.xml
- 2023-07-10 (C) Questetra, Inc. (MIT License)
(Installing Addon Auto-Steps are available only on the Professional edition.)
Notes
- How to register an application on the Dropbox side
- Visit the Dropbox developer site (https://www.dropbox.com/developers) and log in
- Under ‘1. Choose an API’, select ‘Scoped access’
- Under ‘2. Choose the type of access you need’, select either ‘App folder’ or ‘Full Dropbox’ depending on the intended use
- Under ‘3. Name your app’, enter a name (any name is OK)
- Create an app under ‘Create app’
- In the Settings tab, enter ‘https://s.questetra.net/oauth2callback’ in ‘Redirect URIs’ and add it
- Note down the App key and App secret in the Settings tab (used in the Questetra side settings)
- In the Permission tab, click ‘files.content.write’ (authorisation required) and Submit
- How to Configure HTTP Authentication Settings on the Questetra side
※ Reference page: Understanding HTTP Authorization Settings (https://support.questetra.com/developer-blog/http-auth-setting/)- Select ‘OAuth2’
- Name: Dropbox (any name is acceptable as long as it matches the OAuth2 settings in the add-on XML on the workflow application side)
- Authorized endpoint URL: https://www.dropbox.com/oauth2/authorize?token_access_type=offline
- Token endpoint URL: https://api.dropboxapi.com/oauth2/token
- Scope: (not specified)
- Client ID: (Specify the App key obtained by the Dropbox side settings)
- Client secret: (Specify the App secret obtained from the Dropbox side configuration)
- An error occurs if you try to upload a file with the same name while the “Overwrite existing files?” option is disabled.
Capture
