Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
This repository was archived by the owner on Oct 6, 2021. It is now read-only.
/file-pickerPublic archive

The Kloudless File Picker is a file chooser and uploader for apps that integrates with 20+ cloud storage services with a few lines of code

License

NotificationsYou must be signed in to change notification settings

Kloudless/file-picker

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Sign up for a free account athttps://kloudless.com to obtaina Kloudless App ID to initialize the File Picker with. The File Picker is built onour unified Storage API abstraction layer(Cloud Storage REST API docs here).

TheKloudless File Picker is a JavaScript librarythat allows your users to browse and select files and folders from the followingstorage services:

Services
Adobe CQ5Alfresco CloudAlfrescoAmazon S3
Azure StorageBoxCMISCitrix Sharefile
DropboxEgnyteEvernoteFTP
Google DriveHubSpot FilesJiveOneDrive for Business
OneDriveSMBSalesforce FilesSharePoint Online
SugarSyncWebDAV

Table of Contents

Usage

Initializing a File Picker

The File Picker JavaScript library can be imported into web applicationsand launched when a user clicks an element.

Import from a script tag

Include the Kloudless File Picker JavaScript library on your HTML page usinga script tag that points to our CDN:

<scripttype="text/javascript"src="https://static-cdn.kloudless.com/p/platform/sdk/kloudless.picker.js"></script>

This exposes a globalKloudless.filePicker object you can use to initializea File Picker. Check out the Configuration Options section further below fora full list of configuration options.

<scripttype="text/javascript">varpicker=window.Kloudless.filePicker.picker({// File Picker initialization options here.app_id:"Your App ID",// Get your own at https://kloudless.com});</script>

Import from an ES6 module

You can also install the File Picker package from NPM:

npm install @kloudless/file-picker
importfilePickerfrom'@kloudless/file-picker';constpicker=filePicker.picker({app_id:"YOUR_APP_ID"});

Launching the File Picker

Here is a basic example of a button that launches the File Pickergiven the JavaScript above that creates apicker object.

<body><buttonid="choose-files">Choose Files</button><scriptsrc="https://static-cdn.kloudless.com/p/platform/sdk/kloudless.picker.js"></script><script>varpicker=window.Kloudless.filePicker.picker({app_id:"APP_ID"});picker.choosify(document.getElementById('choose-files'));</script></body>

The HTML above adds a specificid to an element so that wecan reference it later in our JavaScript that launches the File Pickerwhen the element is clicked. A more complete example is presentbelow after the full list of configuration optionsas well as on ourdemo page.

Be sure to serve the page via a web server, as pages opened via thefile URI scheme (file://) cannot receive postMessage messagesfrom theiframe created to display the File Picker due to securityconcerns.

File Picker Modes

The File Picker can be configured to either be a filechooser toselect files and folders from cloud storage or the local computer, or a filesaver to export a specific file to cloud storage.

Chooser

The Chooser allows your application to prompt a user to select files or a folder,and retrieves metadata about the files or folder selected.It supports choosing files from the local machine as well as cloud storage.Your application can also upload files to users' cloud storage using theUpload API endpointafter prompting users to select a folder to upload data to.

The Chooser is therefore a popular option for both importing files to yourapplication as well as exporting them to specific destinations in cloud storage.

Dropzone

The Dropzone is a variety of the Chooser that opens when files are dragged anddropped into it rather than only when clicked. See theDropzonesection for more information.

Saver

The Saver allows your application to prompt a user to select a folder to savea specific file to. This lets your application save some work over the Chooserby automatically handling the upload to cloud storage given a link to the file.However, only a single file is supported at a time.

The Saver returns metadata on the newly uploaded file to the application.

Configuration

The File Picker has several configuration options. Below, we've includedoptions that can be set on the library inclusion tag itself, options that applyto both the Chooser and Saver modes, and options that are specific to aparticular mode.

Script tag

The following attributes can be set on the<script> tag used to include theFile Picker JavaScript on the page.

  • data-kloudless-object : string

    Optional. By default, thefilePicker object will be exposed towindow.Kloudless.filePicker.

    Specifies a different name for thefilePicker object bound towindow.e.g.data-kloudless-object="filePicker2" would make the filePickerobject accessible viawindow.filePicker2. Do not use theasync attributeon the script tag if this is used.

Chooser and Saver

  • app_id : string

    Chooser:Required

    Saver:Required

    The application ID is specific to the developer's application and is locatedin the developer portal on the App Details page.

  • element : string or HTMLElement

    Chooser:Optional (default: null)

    Saver:Optional (default: null)

    Specify a CSS selector string or DOM element to attach the File Picker toinstead of displaying the File Picker as a modal (the default).If a string is provided, it will be used to retrieve the DOM element by usingdocument.querySelector.

  • retrieve_token : boolean

    Chooser:Optional (default: false)

    Saver:Optional (default: false)

    This option will includeBearer Tokensin addition to the other response data, to allow you to make further requests to the APIor save the OAuth Tokens for future use.

    // Example response with an OAuth Token in the metadata.[{bearer_token:{key:"the_token",},  ...}]

    Only File Pickers launched from Trusted Domains can make use of this option.You can add a Trusted Domain on the App Details page.

    In addition, care shouldbe taken to ensure no malicious JavaScript or XSS vulnerabilities are presenton the page, as the Bearer Token provides complete access to that user's account.

  • persist : string

    Chooser: "none", "local", "session" (default: "local")

    Saver: "none", "local", "session" (default: "local")

    This option specifies how to persist connected account information, such asBearer tokens to access the Kloudless API.

    The File Picker will fall back tolocal if an invalid option is specified,and fall back tonone if eitherlocalStorage orsessionStorage are notaccessible.

  • services : array

    Chooser:Optional (default: ['file_store'])

    Saver:Optional (default: ['file_store'])

    This option specifies which services to allow a user to explore. You can enumeratethe specificservices oruse a service group listed below as a shortcut.The default is thefile_store service group. If you specify an empty array,no services will show up.

    Service groups:

    • file_store: All File Storage services.
    • object_store: All Object Storage services.
    • construction: All Construction services.
    • all: All storage services.
  • account_management : boolean

    Chooser:Optional (default: true)

    Saver:Optional (default: true)

    Iffalse, hides the Account menu entry in the dropdown. This can becombined with thetokens option to ensure a user only browses a pre-definedlist of accounts and also does not disconnect any of the accounts. If accountdisconnection is permitted, setservices to[] rather than disabling theaccount_management option.

  • display_backdrop : boolean

    Chooser:Optional (default: false)

    Saver:Optional (default: false)

    Iftrue, displays a shadow backdrop behind the File Picker, and prevents thepage body from scrolling.

  • locale : string

    Chooser:Optional (default: "en")

    Saver:Optional (default: "en")

    The Kloudless File Picker supports i18n/l10n. You can specify any of thefollowingISO-639-1 codes:

    ar,az,bs,cs,cy,da,de,el,en,es,et,fa,fi,fr,he,hr,hu,hy,id,it,ja,ka,kk,km,ko,lt,lv,mn,ms,nl,pl,pt,ro,ru,sk,sq,sr,sr,sv,th,tr,uk,zh-CN,zh-TW

    The locale is used to identify thedata to retrieve from eitherthe data provided in thetranslations option below or from the out-of-the-boxtranslation data in themessages directory.If no translation data is found, the File Picker uses theen locale.

  • translations : string or object

    Chooser:Optional (default: "")

    Saver:Optional (default: "")

    This option specifies either an object with translation data or a URLthat returns the translation data as a JSON string. Thelocale optionindicates which locale's translation data to use. Any translation dataprovided here overrides Kloudless' default translation data included in themessages directory.Seetranslations-suite-sample.jsonfor an example of the translation file format.Any strings not translated will default to theen locale's representation.

  • dateTimeFormat : string

    Chooser:Optional (default: "MMMdHm")

    Saver:Optional (default: "MMMdHm")

    This option specifies a date-time format for thelocale above.Please refer to theskeleton values in theglobalize JS modulefor the formats supported.

  • create_folder : boolean

    Chooser:Optional (default: true)

    Saver:Optional (default: true)

    Iftrue, the user will be able to create folders in their cloud storageaccounts.

  • account_key : boolean

    This option is deprecated as OAuth 2.0 Tokens are used to authenticated accountsnow instead of Account Keys. Please use theretrieve_token option below instead.Existing Account Keys can be converted to OAuth Tokens usingthis endpoint.

  • keys : array

    This option is deprecated as OAuth 2.0 Tokens are used to authenticated accountsnow instead of Account Keys. Please use thetokens option below instead.Existing Account Keys can be converted to OAuth Tokens usingthis endpoint.

  • tokens : array

    Chooser:Optional (default: [])

    Saver:Optional (default: [])

    This option should listOAuth 2.0 Tokensfor accounts the File Picker should be initialized with. The File Picker willmake API requests for additional information on the accounts and display themin the list of accounts the user has connected.

    {tokens:["abcdefghijklmn","opqrstuvwxyz"],  ...// other options}
  • enable_logout : boolean (default: true)

    Iftrue, allows users to log out of their accounts, which deletes the accountfrom Kloudless servers. API requests will no longer be possible to the account.

  • delete_accounts_on_logout : boolean (default: false)

    Iffalse, the File Picker only removes tokens from the storage configuredinpersist option when users log out. Iftrue, it also deletes the accountsfrom the Kloudless server and invalidates the OAuth tokens.

  • oauth : function (default:see below)

    Use this parameter to customize the query parameters used in the first leg ofthe Kloudless OAuth flow when authenticating users.A full list of parameters supported is available on theOAuth docs.

    By default, thescope the File Picker uses is"<service_id>:normal.storage <service_id>:normal.basic". Note that thefollowing options cannot be overridden for consistency or security reasons:

    • client_id,
    • response_type
    • redirect_uri
    • origin
    • state

    Set the value of theoauth option to a function that accepts a string.The function will be called when a user attempts to connect an account, withthe string argument being theidentifierof the service the user is attempting to connect. For example,gdrive.

    The function should return an object representing the attributes toinclude as query parameters in the OAuth flow. Don't URL-encode the values;the File Picker handles that. Here is an example that customizes theOAuth permissions requested if a user attempts to connect a Google Driveaccount, and also pre-fills the server URL if a user chooses to connect an FTPaccount:

    {oauth:(service)=>{constauthOptions={};switch(service){case'gdrive':// Ask for read-only access to Google Drive data instead.authOptions.scope='gdrive.storage."https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/drive.readonly":raw';// Pass additional query parameters to Google Drive.authOptions.raw={'query_name':'query_value'};break;case'ftp':// Set a default domain when connecting an FTP account.authOptions.form_data={domain:'ftps://ftp.example.com:21',};break;}returnauthOptions;},  ...// other options}

    If you're familiar with the configuration options accepted by theKloudless Authenticator,the File Picker requires options returned in the same format that theAuthenticator accepts. For convenience, the followingsupported parameterscan be specified as objects as shown in the example above:

    • form_data (converted to a URL-encoded JSON string)
    • custom_properties (converted to a URL-encoded JSON string)
    • raw (converted to theraw[key]=value format described in the docs)
  • custom_style_vars : object

    This project uses LESS as a CSS pre-processor. Since LESS can be run in thebrowser, we support overriding CSS global variables dynamically to customizestyling. For example, change the primary color by settingmain_color:

    {custom_style_vars:{main_color:"black"}}

    Please refer tovariables.less for thefull list of available variables. Most are related to aspects such as colors,fonts, or dimensions. Specifying the@ prefix for each variable is optional.

    For further customization, we recommend forking this project and hostingthe resources on your own, since we don't guarantee backward-compatibilitywhen overriding undocumented variables.

  • root_folder_id: object

    Chooser:Optional (default: {})

    Saver:Optional (default: {})

    This option is used to specify a specific folder as the root folderfor any existing account browsable via the File Picker. This is helpful forscenarios where the user may not have access to the root or other high-levelfolders but does have access to specific known folders within the account.This option accepts a map of the Kloudless Account ID to the Kloudless FolderID in the format{[account_id]: "root_folder_id"}, as shown below:

    {1234:"folder_abc1234",5678:"folder_somefolder5678"}

    The example above sets the root folder tofolder_abc1234 for account1234 andfolder_somefolder5678 for the account5678.

    When connecting or switching to an account that has a root folder IDconfigured, the default folder opened will be the specified folder ratherthan the usual root folderroot. The File Picker UI won't enable navigationoutside of the chosen root folder, although it may be accessible to the uservia direct API requests. This configuration option should therefore not beused to limit access for security purposes.

    For existing accounts, be sure to also use thetokens attribute to specifythe Bearer tokens to use to browse the account. Ifaccount_management isenabled (the default), the user may also connect new accounts. Since theroot folder ID is not possible to provide in advance until the newlyconnected account's ID is known, please first listen for theaddAccountevent, then perform API requests to determinethe ID of the root folder to display, and finally call thepicker.update()method with the updated configuration that includes the rootfolder ID for the newly connected account within it:

    letroot_folder_id={};// Any existing root folder IDspicker.on('addAccount',account=>{// Set `retrieve_token: true` in the config to retrieve the Bearer token// to use in API requests to determine the right root folder ID, and// then include that root folder ID below.root_folder_id[account.id]='root';picker.update({ root_folder_id});});

    Here is an example of limiting users connecting SharePoint accounts to onlyselecting files from within the primary document library of the main sitecollection:https://jsfiddle.net/kloudless/uwax8tqy/.

    The example above uses a known folder ID based on a consistent location within theSharePoint tenant, but most folders' IDs are random and must be obtained dynamically.To obtain the Kloudless Folder ID for an upstream folder path, pleaseuse theEncode Raw Data API endpointor list the contents of the account, beginning at theroot, until the requiredfolder's metadata is obtained.

    Note: Search requests may still return results outside the root folderspecified for services that do not support theparentsquery parameter.

  • close_on_success : boolean (default: true)

    Defaults totrue, which closes the File Picker when all the selections inthe Chooser have been processed successfully, or when all the files in theComputer view or the Saver have been uploaded successfully.

    Iffalse, the user will see a success message rather than the FilePicker closing.

    For the Chooser and the Saver, if theelement option is specified, thisoption will always befalse. For the Dropzone, this option is alwaystrue.

Chooser Options

  • multiselect : boolean

    Chooser:Optional (default: false)

    This option allows a user to select multiple files or folders from cloudstorage or their local device. The Chooser will return a list of one or moreentries. Selecting multiple folders is not currently supported on mobiledevices.

  • computer : boolean

    Chooser:Optional (default: false)

    Dropzone:Always true

    This option allows users to upload files directly from their computer.Note: If you plan to build and host the file-picker on your own, this optionis only available for theAGPL build.

    Configuring the Chooser's Upload Location

    The Chooser will upload files to the developer's Upload Location.The Upload Location can be set in thedeveloper portal.Under 'UI Tools' tab, click 'File Picker' and follow the instructions forselecting a folder in a storage service such as Amazon S3. All local filesfrom a user will be uploaded there.

  • link : boolean

    Chooser:Optional (default: false)

    Iftrue, generates a link to the selected file(s). The link will be providedin thelink key of the response sent to thesuccess event. For asynchronousrequests, the result of theKloudless Taskwill contain the link instead.

    Use with thecopy_to_upload_location option to generate a link to the newlycopied file.

    The Kloudless File Picker will fire theerror event if the linkgeneration fails.

    // Success event result when `link` is true:[{"link":"https://<the file link>",  ...}]
  • link_options : Object

    Chooser:Optional (default: {})

    Thelink_options object provides parameters to use when the File Pickercreates links. See thedocumentation for creating linksfor a full list of the possible options available.Note that links to selected files are only created if thelinkconfiguration option is set totrue. In addition, files with thedownloadable attribute set tofalse cannot be downloaded sothey cannot be selected iflink_options.direct istrue.

    For example:

    {link_options:{direct:true,expiration:"2020-10-12T00:00:00"},  ...// other options}
  • copy_to_upload_location : string

    Chooser:Optional (default: null)

    If this option is set, it will copy any file or non-root folder selected bythe user from cloud storage to the location that files uploaded from theuser's computer are placed in.

    Since the file must be able to be downloaded for this to occur, only fileswith thedownloadable attribute set totrue can be selected when thisoption is enabled. When copying folders, the non-downloadable files willbe skipped.

    An Upload Location must be configured via the developer portal to make use ofthis option.

    This option accepts two values:

    • 'async': Triggers an asynchronous copy and immediately returns a Task IDin thesuccess event callback that can be checked using theKloudless Task APIfor the copied file or folder's metadata.

      The Kloudless Task API returns a Task object that includes progressinformation until the task finishes.
      When the task finishes, the API endpoint returnsFileorFolderobject instead.
      If the task fails, the endpoints returns anError.

      Here is an example of polling for the result of a task using jQuery:

      functionpollingTask(taskId,accountToken,delay){returnnewPromise((resolve,reject)=>{setTimeout(()=>{$.ajax({url:`https://api.kloudless.com/v1/accounts/me/tasks/${taskId}`,headers:{Authorization:`Bearer${accountToken}`},}).done(resolve).fail(reject);},5000);// Poll every 5 seconds});}picker.on('success',async(results)=>{// Assume the user only selects one item.const[{id:taskId,// Should enable `retrieve_token` option to get bearer_token.bearer_token:{key:accountToken},},]=results;try{letresponse=awaitpollingTask(taskId,accountToken);while(response.id===taskId){// Task has not finished yet, so keep polling.response=awaitpollingTask(taskId,accountToken);}// Task has finished.console.log(response);}catch(jqXHR){if(jqXHR.responseJSON){// Kloudless API Server returned an error.console.error(response.responseJSON);}}});
    • 'sync': Triggers a synchronous API request to copy the file or folder andpolls till the copying is complete. Thesuccess event callback receivesthe newly uploaded file or folder's metadata.

    The deprecatedtrue option is only available for copying files and willreturn the new file's hypothetical metadata even though the copy has not yetcompleted. Please migrate to using'sync' instead for similar behavior witha guarantee that the copy is successful.

    The Kloudless File Picker will fire theerror event if the copyoperation is not completely successful.

  • upload_location_account : string

    Chooser:Optional (default: null)

    If multiple Upload Locations are configured via the developer portal, thisspecifies the Account ID of the Upload Location to use. This option is notrequired if only one Upload Location is configured. The Account ID is a numberthat can be found in the File Picker Upload Locations section of theDeveloper Portal page.upload_location_folder must also be provided.

  • upload_location_folder : string

    Chooser:Optional (default: null)

    If multiple Upload Locations are configured via the developer portal, thisspecifies the Folder ID of the Upload Location to use. This option is not requiredif only one Upload Location is configured. The Folder ID is an encoded string thatcan be found on the File Picker Upload Locations section of theDeveloper Portal.The ID of a sub-folder may be specified if the option is enabled in theDeveloper Portal.upload_location_account must also be provided if more thanone upload location exists.

  • uploads_pause_on_error : boolean

    Chooser:Optional (default: true)

    Iftrue, uploads using the Computer option will pause if errors are encountered,giving the user the option to retry the upload by clicking 'Resume'. The user couldalso remove the file that is failing to upload from the queue.Iffalse, the file that encounters errors will be skipped and excluded from thelist of files returned in thesuccess callback.

  • types : array

    Chooser:Default: ['all']

    This option specifies which types of elements the File Picker will show to theuser. You can filter based on file extension or by the following categories:

    • all This configures the File Picker to show all file types and folders.The user can select either files or folders. Do not combine with other options.

    • folders This configures the File Picker to gray out files and show folders.The user can only select folders.

    • files This configures the File Picker to show all file types. The user canonly select files.

    • text

    • documents

    • images

    • videos

    • audio

The categories will be translated to the corresponding file extensions and MIMEtypes internally. CheckTYPE_ALIAS andMIME_TYPE_ALIAS inconstants.js for the specific file extensionsand MIME types mapped to.

You can also specify file extensions as well as MIME types by including themin the array without the period (.) prefix. For example,['pdf', 'jpg', 'jpeg', 'png', 'application/vnd.google-apps.document'].

Include'' to allow files with the MIME typeapplication/octet-stream orwithout a file extension to be selected.

  • max_size : number

    Chooser:Optional (default: 0)

    The maximum size (in bytes) of files that can be selected, or uploaded in thecase of local uploads via the Computer option. This limit applies per fileselected, and not collectively.

    Set to0 to disable this limit.

    Files with an unknown size, such as Google Docs, can still be selectedregardless of this option.

Saver Options

  • files : array

    Saver:Optional (default: [])

    This option should list files for the File Picker to save. The formatshould be an array of Javascript Objects containing a file url and name.You can specify up to 100 files. Each file will be uploaded via the KloudlessAPI'supload endpoint,using theurl attribute.

    {files:[{url:"http://<your image url>",name:"filename.extension"},{url:"http://<your image url>",name:"filename.extension"}],  ...// other options}

Events

  • success(results)

    Fired when the user's selections in the Chooser are processed successfully, orfiles are uploaded successfully via the Chooser's Computer option or Saver.
    Thesuccess event is still fired even if only part of the items weresuccessfully chosen or saved.

    results is an array ofFileorFolderobjects that were successfully selected.

    Whencopy_to_upload_location is set toasync,results will instead bean array of Task objects returned by theKloudless Task API.

    The File Picker closes once this event has triggered.

  • cancel()

    Fired if the user decides to cancel an operation. The File Picker willbe closed on cancellation.

  • error(results)

    Fired when any of the selections fail to process or any of thefiles being uploaded fail to upload successfully.
    Theerror event is still fired even if only part of the items failed tobe chosen or saved.

    results is an array of failed objects. The object structure varies basedon usage. For the selections in the Chooser, the object is aFileorFolderobject.

    For uploads via the Chooser's Computer option or Saver, the object is thesame as that for thestartFileUpload event mentioned below.

    An additional key,error, is added to the object metadata and includesthe error returned from theKloudless APIdescribing why the operation failed.

    Here is an example of theerror object:

    {"status_code":404,"message":"File not found: 1D-QuGwx7acbeGQ3STSCphysJsQs8YHJR","error_code":"not_found","id":"9b62d9d8-7bc7-495b-b97a-33b43720274d"}
  • open()

    Fired when the File Picker is displayed to the user. This occurs whenthe Chooser or Saver are opened.

  • close()

    Fired when the File Picker is hidden from the user. This occurs whenthe File Picker is closed. This could be due to either a user action,such as choosing files or cancelling, or due to theclose() methodbeing called (not to be confused with thisclose event handler).Thesuccess orcancel events will also be fired if appropriate.

  • selected(results)

    Fired when the user selects files or folders from theFile Picker, but before the list is sent to the Kloudless API for additionalprocessing. This means this event fires before thesuccess event,and allows you to perform any action while waiting to get the final list.

    Ifcopy_to_upload_location andlink are both disabled, then this event isequivalent to thesuccess event (since nothing needs to happen on theserver after the selections are made), so this event serves no purpose then.

    results is an array ofFileorFolderobjects.

    This event is not fired when the user uses the Chooser's Computer option orthe Saver. SeestartFileUpload andfinishFileUpload for events firedin those cases.

  • addAccount(account)

    Fired when a user successfully connects an account.account is an object containing the account ID, name, and service ID.

    Here is an example:

    {"id":123456,"name":"user@domain.com","service":"gdrive"}
  • deleteAccount(accountId)

    Fired when a user successfully removes an account.

  • startFileUpload(file)

    Fired when a file upload starts, or is requested to be retried by a userafter encountering errors (see theuploads_pause_on_error option).This event is only fired when the user uploads a file via the Chooser'sComputer option or the Saver.

    For the Chooser's Computer option, thefile object has the followingattributes:

    • id A randomly generated ID.
    • name The uploaded file's name.
    • size The uploaded file's size.
    • mime_type The uploaded file's MIME type.

    Here is an example:

    {"id":"o_1efeta5ej5ac1v4t139e39l1ldka","mime_type":"image/jpeg","name":"15224125762.jpeg","size":9834}

    For the Saver, thefile object has the following attributes instead:

    • url The file URL specified in the Saver's launch options.
    • name The file name specified in the Saver's launch options.

    Here is an example:

    {"url":"https://s3-us-west-2.amazonaws.com/static-assets.kloudless.com/static/kloudless-logo-white.png","name":"kloudless-logo.png"}

    This event is fired once per file and not per uploaded chunk.

  • finishFileUpload(file)

    Fired when a file upload completes successfully (once per file beinguploaded). Thefile object contains the same information as provided tothestartFileUpload event above, with an additional keymetadatawhose value is the resultingFile.

    This event is only fired when the user uploads a file via theChooser's Computer option or the Saver.

  • logout()

    Fired when the user clicks the logout link in the File Picker, whichclears the local state of accounts connected to the File Picker.

  • drop()

    Fired when drops files into Dropzone.

Methods

  • filePicker.picker(options)

    You can initialize a Kloudless File Picker using the options mentioned above.

  • filePicker.getGlobalOptions()

    Getbuild options. These are options configured whenthe File Picker JavaScript library was initially built. See theSelf-Hosting section for more information.

  • filePicker.setGlobalOptions(buildOptions)

    Changebuild options during run-time. The widget isconfigured to work with default values, so these options should only be setwhen needed.

  • picker.choose()

    This method allows you to launch a Chooser.

  • picker.choosify(element)

    This method binds a click handler that launches the Chooser to the DOM element.

  • picker.save(files)

    This method allows you to launch a Saver. SeeSaver Options for more informationon the format forfiles.

  • picker.savify(element, files)

    This method binds a click handler that launches the Saver forfiles to theDOM element.

  • picker.on(event, callback)

    Invokes a callback method on a particular event. See theEvents section abovefor a list of event names, as well as the arguments the corresponding callbackmethods will be invoked with.

  • picker.close()

    This method closes the File Picker window.

  • picker.update(options)

    Updates the configuration options the File Picker was initialized with. TheFile Picker will immediately begin using the new configuration.options is an Object with the new configuration. Not all options can beupdated in this manner. The following are not supported:

    • app_id
    • types
    • services
    • persist
    • create_folder
    • account_key
    • custom_style
    • custom_css (deprecated)
    • locale
    • element
    • max_size
  • picker.logout(deleteAccount=false)

    Removes all authentication tokens for the accounts connected to the FilePicker as configured via thepersist option. IfdeleteAccount is settotrue, it also deletes the accounts from the Kloudless server andinvalidates the OAuth tokens, rendering them unusable and the accountsinaccessible.

    This method isn't impacted by thedelete_accounts_on_logout option.

  • picker.destroy()

    Destroy the file picker instance. It includes closing the file picker,removing the EventListener, and removing the DOM including the file pickeriframe.

    This method won't clean up localStorage/sessionStorage, so theauthentication tokens won't be removed.

Script tag example

To start using the File Picker, simply include the JavaScript file in yourHTML file. You can then create an element on the page to launch the File Picker.

<body><buttonid="file-picker-button">Open File Picker</button><scripttype="text/javascript"src="https://static-cdn.kloudless.com/p/platform/sdk/kloudless.picker.js"></script><scripttype="text/javascript">// File Picker initialization JS here.</script></body>

The next step is to customize the File Picker according to the developer's needs.In this example, we've decided to disable multiselect, return links, and allow fora few types of files. All of this is contained within the initialization.

// File Picker initialization JSvarpicker=window.Kloudless.filePicker.picker({app_id:'YOUR_APP_ID',multiselect:false,link:true,types:['images','documents','text']});

The final step is to launch the File Picker and handle the events returned fromthe File Picker based on a user's actions.

Visit our demo of the File Picker!

// When a user successfully selects or saves a filepicker.on('success',function(files){// files is an array of JS objects that contain file metadata.console.log('Successfully selected files: ',files);});// When a user cancels the File Pickerpicker.on('cancel',function(){console.log('File selection cancelled.');});// Launching the File Picker to choose when a user clicks the 'Open File Picker'// button.picker.choosify(document.getElementById('file-picker-button'));// In addition, you can launch the File Picker programmatically with choose()picker.choose();// Launching the Picker to save when a user clicks the 'Open File Picker' button// Note: you can pass in an array of files instead of using the configuration// optionvarfiles=[{url:'http://<your image url>',name:'filename.extension'},{url:'http://<your image url>',name:'filename.extension'}];picker.savify(document.getElementById('file-picker-button'),files);// In addition, you can launch the File Picker programmatically with save()varfiles=[{url:'http://<your image url>',name:'filename.extension'},{url:'http://<your image url>',name:'filename.extension'}];picker.save(files);

Dropzone

The Dropzone is a variety of the Chooser that allows users to drop files intoit from their Computer rather than only click on it to launch the File Picker.It opens in place when files are dropped into it.

Note: If you plan to build and host the file-picker on your own, the Dropzoneis only enabled for theAGPL build.

Configuration

The configuration is similar to the Chooser's, but requires theelement optionto indicate where to display the Dropzone, as described below. In addition, thecomputer option is always set totrue, and an Upload Location must beconfigured as described for the Chooser.

  • element : string or HTMLElement

    Chooser:Required

    The DOM element to bind the Dropzone to. If a CSS selector string is provided,it will be used to retrieve the DOM element by usingdocument.querySelector.The drop zone will render a 600px * 100px area for the user to drag and dropfiles in. The area's width will adjust automatically when the viewportwidth is lower than 600px.

Methods

  • filePicker.dropzone(options)

    Initialize a Dropzone using the options mentioned above.

  • dropzone.on(event, callback)

    Seepicker.on(event, callback) for more information.

  • dropzone.close()

    Seepicker.close() for more information.

Example

Visit our JSBin example of the Dropzone!

HTML

<divid="dropzone"style="width: 600px; height: 100px;"></div>

JavaScript

vardropzone=window.Kloudless.filePicker.dropzone({app_id:'Your App ID',element:'#dropzone',multiselect:true,// To upload more than 1 file.// Chooser options below:computer:true,link:true,services:['all'],types:['all'],});// All of the Chooser's events are supported.// For example:dropzone.on('success',function(files){console.log('Successfully selected files: ',files);});// See the File Picker's Example section for other events.

File Picker with Vue

SeeFile Picker with Vue.

File Picker with React

SeeFile Picker with React.

Browser Support

  • Chrome 56+
  • Firefox 56+
  • IE 11+
  • Edge 12+
  • Safari 8+
  • Opera 49+

Work with mobile devices

To use the Kloudless File Picker on devices with narrow screens, please add aViewport meta tagto the web page launching the File Picker. This ensures the File Picker uses stylingappropriate for mobile screen sizes.

The meta tag assumes that your entire web page renders well in narrow screenssince it applies to your page as a whole and not just the File Picker.Please test out your page's usability if you are adding the meta tag for thefirst time.

Here is an example meta tag:

<meta name="viewport" content="width=device-width, initial-scale=1">

If your page benefits from preventing some devices such as iPhones fromzooming in on input fields, you can also add in theuser-scalable=no optionas shown below. Input fields such as<input> and<select> are used in theFile Picker as well.

<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">

Migration Guide

From v1 to v2

New Layout and New Options to Customize the UI

v2 represents a new layout and set of options for the File Picker, including:

  • A completely new theme for the UI with improved responsiveness, clearer HTMLand CSS structure with consistent naming conventions, and several bug-fixes.
  • A documented format for customizing UI styling such as colors and fontswithout forking the entire project.

Provided your application isn't already customizing styling by using thecustom_css option as detailed below, it will automatically begin using thenew version.

File Explorer Renamed to File Picker

The File Explorer has been renamed to the File Picker to improve clarity.The entire JS namespace, as well as any relevant method, variable, orconfiguration option names, have been transitioned from referencing an"explorer" to a "picker", while preserving backwards-compatibility.

Here is a table to assist with transitioning previously publicly documentednames to their newer counterparts:

DescriptionOld NameNew Name
namespacewindow.Kloudless.fileExplorerwindow.Kloudless.filePicker
methodexplorer()picker()
global optionexplorerUrlpickerUrl
environment variableEXPLORER_URLPICKER_URL
script tag URLhttps://static-cdn.kloudless.com/p/platform/sdk/kloudless.explorer.jshttps://static-cdn.kloudless.com/p/platform/sdk/kloudless.picker.js

Forked projects that are migrating to v2 should take care to replace namessimilarly.

React and Vue Wrapper Options Configuration

Previously,getGlobalOptions andsetGlobalOption were imported from@kloudless/file-picker as shown below:

importfilePickerfrom'@kloudless/file-picker';filePicker.getGlobalOptions()filePicker.setGlobalOptions({...})

Now, they can be imported from@kloudless/file-picker/react,or@kloudless/file-picker/vue, depending on the framework in use:

import{setGlobalOptions,getGlobalOptions}from'@kloudless/file-picker/react';// Or use the following syntax for VueJS:// import { setGlobalOptions, getGlobalOptions } from '@kloudless/file-picker/vue';getGlobalOptions()setGlobalOptions({...})

Incompatible Configuration Options

Below are some options that will no longer be effective, or will force theprevious version to continue to load instead, to maintain compatibility.

  • custom_css : string

    Chooser:Optional (default: null)

    Saver:Optional (default: null)

    This option is deprecated and no longer supported in the latest versionsof the File Picker. Using this option will result in the File Pickerreverting to a previous layout that supported this option.

    Refer to thecustom_style_vars option to customize styling instead.Alternatively, you may clone this project and self-host it to customize theUI more extensively.

    Previous Notes

    custom_css is an optional attribute that accepts a URL to a stylesheet forthe File Picker to load to override or customize styling.Supports(http|https)://domain.com/path/to.css,//domain.com/path/to.css,and/path/to.css formats.

    To use thecustom_css option, the domain the File Picker is launched frommust be added to the application's list ofTrusted Domains.

From v1.0.0 to v1.0.1

When using the script tag, the target exposed has been updated fromwindow.Kloudless towindow.Kloudless.fileExplorer to better scope our UItools. All the exports underwindow.Kloudless are deprecated and have beenmoved towindow.Kloudless.fileExplorer.

Contributing

Contributions are welcome and appreciated. We'd love to discuss any ideas youhave to improve or extend the File Picker. We recommendcontacting us atsupport@kloudless.comfirst for major modifications that you would like merged in so we canoffer feedback on its implementation.

Requirements

InstallNode.js(sudo apt-get install nodejs or equivalent)
Make sure you have nodejs >= 10.16.0 and npm >= 6.9.0.Then run the following commands:

npm cinpm run install-deps

To develop Vue or React wrapper, you might want to install thecorresponding storybook:

npm ci --prefix=storybook-vue    # for Vuenpm ci --prefix=storybook-react  # for React

Development

Use the following command to set a Kloudless App ID and run the localdevelopment server:

KLOUDLESS_APP_ID=<your_app_id> npm run dev

The File Picker that launches on the test page uses the App ID toconnect accounts. It must therefore be the ID of a valid KloudlessApplication on the Kloudless API server the File Picker accesses.

By default, the development server points tohttps://api.kloudless.com.However, you can point it to an alternate Kloudless API server using theBASE_URL environment variablebuild option as shown below.

# Export this environment variable before the `npm run dev` command above.export BASE_URL=<your_kloudless_api_server_url>

The development server supports automatically rebuilding the source fileswhenever changes are saved. However, hot reloading scripts is not supportedyet; you will need to reload the page to view your changes.

TypeScript Definition

Be sure to updatesrc/loader/js/interface.d.ts if the correspondinginterface is changed.

Build

The command below generates a minified production build at/dist.

npm run build

Here is an explanation of thedist folder's structure:

FolderPurpose
loaderContains the script that an application includes to load the File Picker.
pickerContains the File Picker assets that theloader loads in an iframe. Only customize this whenself-hosting the File Picker.

The above command generates a build licensed under MIT by default. If you wantto self-host the File Picker, please note that the Computer option andthe Dropzone are only available in an AGPLv3 licensed build. For more details,refer to theLicense section. To get an AGPLv3 licensed build, run

npm run build:agpl

, or customize your build by providing thebuild optionBUILD_LICENSE=AGPL.

Build Options

The options below can be set during the build process as environment variablesto customize the build, or sometimes at run-time as well.

Build-time Env VarRun-time optionDescriptionDefault
BASE_URLbaseUrlURL to the Kloudless API Serverhttps://api.kloudless.com
PICKER_URLpickerUrlThe URL that the loader loads the file picker iframe from.https://static-cdn.kloudless.com/p/platform/file-picker/v2/index.html
BUILD_LICENSEN/AMIT orAGPL. See theBuild section.MIT

Check out theSelf-hosting section below for an examplethat changes thePICKER_URL in order to self-host a customized forkof the File Picker.

In addition, here is an example that directs API requests from the File Pickerto an alternate Kloudless server:

BASE_URL=<your_kloudless_api_server_url> npm run build

Testing

To test the build generated bynpm run build, run the following command:

KLOUDLESS_APP_ID=<your_app_id> npm run dist-test

To test the TypeScript definition file, run the following command:

npm run test:ts

Test in Legacy Microsoft Edge or Internet Explorer 11

Microsoft providesWindows 10 virtual machinesthat can be used to test the File Picker in Legacy Microsoft Edge and InternetExplorer 11. Note that the development server won't be accessible athttp://localhost:3000 by default becauselocalhost translates to127.0.0.1which points to the VM itself instead of the host running the developmentserver. To work around this, determine the actual IP address of the host runningthe development server, such as10.0.2.2 when using VirtualBox, and editC:\windows\system32\drivers\etc\hosts as an Administrator to add a recordthat mapslocalhost to that IP.

Self-hosting

Self-hosting the File Picker is one way to customize all aspects of theFile Picker's layout, styling, and functionality beyond what theconfiguration and theming options provide.

You can fork the File Picker to make the changes you need beforebuilding the File Picker, which results in a JS file atdist/loader/loader.min.js. This file must be included in any page you wouldlike to use the File Picker on. It serves as a light-weight wrapper to loadthe actual File Picker page via an iframe.

Both the loader file and the rest of the File Picker's structure are discussedin more detail in theBuild section above.

Hosting the File Picker Page

The build contains anpicker folder which includes the actualHTML and functionality of the widget. By default, this is hosted by Kloudless.

If you would like to host this page yourself to customize the core File Pickersource code or styles, follow the steps below:

  1. Rebuild the assets while settingPICKER_URL to specify the File Pickerpage URL. For example, if you'd like to host the File Picker assets athttps://example.com/kloudless/index.html, run the following command:

    PICKER_URL=https://example.com/kloudless/index.html npm run build

    Optionally, you can also setKloudless.filePicker.setGlobalOptions atrun-time instead of re-building the loader:

    Kloudless.filePicker.setGlobalOptions({pickerUrl:'https://example.com/kloudless/index.html',});
  2. Copy the entiredist/picker folder into your web application's assets sothedist/picker/index.html page can be found at the URL specified inthe step above. In the example above, copydist/picker to/kloudlessforhttps://example.com/kloudless/index.html to exist.

  3. Add your web app's domain to your Kloudless App's list ofTrusted Domains on theApp Details Page.This allows the hosted File Picker to receive access tokens to the KloudlessAPI.

  4. Includedist/loader/loader.min.js in your pages that will launchFile Picker as shown in thescript tag example above.

Extending the File Picker Template

This section contains advanced concepts that are not usually required in afork of the File Picker.

Thetemplate/picker.ejs template contains necessary styles and scriptsfor the File Picker as well as the compiled HTML snippets.

Feel free to add additional styles, scripts, or HTML elements you need.You can then runnpm run build:template to build your customizedFile Picker template. The built page will be available atdist/custom-index.html. Replacedist/picker/index.html with this file, and follow the steps in thesection above to host this page instead.

For an example, runnpm run build:template without any changes andcheck the result atdist/custom-index.html.

Misc. Development Notes

  • In order to switch folders, we change the current() pointer and thenrefresh(). refresh() will abort any currently active requests to prevent raceconditions
  • Put buttons that can be clicked repeatedly into data-bind clicks instead ofthe router, because the hash will prevent the route from being fired twiceconsecutively. Use the hash to switch between pages of the application.

Security Vulnerabilities

If you have discovered a security vulnerability with this library or any otherpart of Kloudless, we appreciate your help in disclosing it to us privately byemailingsecurity@kloudless.com.

License

The source code is licensed under the terms of theMIT. Pleasenotice that our library has an optional dependency@kloudless/file-picker-plupload-module,which is licensed underAGPLv3. If you want to buildthe file-picker on your own, the default build is MIT licensed, which meansthe file upload module is excluded, and thus the Computer option andthe Dropzone are disabled. If you want to make an AGPLv3 build with the@kloudless/file-picker-upload-module, please refer to theBuildsection. If you want to modify the AGPLv3 licensed build withoutpublishing your source code, please contact us for a commercial license.

Support

Feel free to contact us atsupport@kloudless.com with any feedback orquestions.

About

The Kloudless File Picker is a file chooser and uploader for apps that integrates with 20+ cloud storage services with a few lines of code

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

[8]ページ先頭

©2009-2025 Movatter.jp