It can be challenging to pull data from multiple sources and assemble it into a uniform output. In those situations, a source plugin will get the job done by fetching the file data from a remote location and leaving a trail of file names for your users. As a developer, you’ll need to access the contents of a JS file upload, which means installing the dependencies that allow your custom plugin to run smoothly.
On its own, the File Picker is packed with uploading functionality, so you can build a better user experience to eliminate request latency. It enables Intelligent Ingestion to reduce chunk size and push parts out even under poor network conditions. A JavaScript file upload API has the solution to your configuration troubles with mounted methods to perform common upload actions, like returning file instances or showing a summary of the added files.
Does Filestack’s ‘Custom Source’ Generate A Dynamic JS File Upload?
Yes, the custom source feature lets developers test the layout of their JavaScript file upload to decide whether the elements are easy to navigate. Moreover, they can configure aspects of the File Picker beneath the API key: the upload source, max number of files, and callback methods.
By default, Filestack’s file picker comes with integrations such as Google Drive, Facebook, and Instagram. The upload options resemble widgets for passing in multiple files, restricting file types, changing image dimensions, and processing transformations.
Most types of file upload API in JavaScript will create a file instance from the URL, DOM, or a native object. And yet, Filestack is quite different because it delivers files stored in an Amazon S3 bucket. It creates a unique URL for each upload, pointing back to its own CDN.
Each custom file object has a URL path, mimetype, file/display name, thumbnail, and headers. The files will actually remain cached for up to 30 days in a secure location.
Import the FsExamplePicker library and add this line to set up the plugin:
const customSource = new plugins.FsExample().toSource();
How Do You Use A Mounted Parameter In Your Custom Source For A JS File Upload?
In this section, we will use the picker plugin to design a common use case of the uploader. First, you need to name the custom source by referring to the following template. To create a list of file previews, define an array of the URL and item name to extract them from the source.
Sample code of a custom source object:
const customSource = {
label: ‘My Custom Source’,
name: ‘MyCustomSource’,
icon: ‘<svg>Insert Icon.svg Path</svg>’,
mounted: (element, actions) => {
},
unmounted: (element) => {
}
}
Mounted methods are called by targeting an element with a given action via the parameters. Once a user clicks on the interface, the source element will grab the raw file data, URL metadata, summary view, file object, or file instance based on the “actions” method.
The unmounted attribute is where you call functions to remove a user session or clear the browser memory after all files have been deployed.
Passing a custom source to the File Picker:
const apikey = YOUR_APIKEY;
const client = filestack.init(apikey);
const options = {
fromSources: [ ‘local_file_system’, customSource, ‘googledrive’, ‘unsplash’, ‘facebook’, ‘instagram’]
maxFiles: 20,
uploadInBackground: false,
onUploadDone: (res) => console.log(res),
};
const picker = client.picker(options);
picker.open();
});
Under options, you can limit the number of files allowed per upload session. Afterward, you can print to the console showing a “file opened” message. Try to load the UI of a JS file upload: Make sure the items were appended in the order of your requests.
How Do You Add Files To The Picker After The User Clicks?
A button would enable users to confirm their selection. The next step is to assign a click event to your “View/Edit” button so it detects which files the user picked. To achieve this, use a click handler to get the index (idx) of every element’s source URL.
sourceUrlsArray.forEach((element, idx) => {
const li = document.createElement(“li”);
const span = document.createElement(“span”);
li.dataset.idx = idx;
li.setAttribute(‘id’, `file-${idx}`)
const thumb = document.createElement(“img”);
thumb.setAttribute(“src”, element.url);
thumb.width = “20”;
thumb.height = “20”;
li.appendChild(thumb);
span.innerHTML = `${element.name}`;
li.appendChild(span);
li.addEventListener(‘click’, handleClick);
list.appendChild(li);
});
element.appendChild(list);
Then, run a forEach() function that iterates over them to create a <li> and <span> item. Now, set the id attr to a “file-${idx}” with li.setAttribute(). For the thumbnail, create an <img> element and set src = element.url before you specify the width and height values.
Use the li.appendChild() function to pass in the thumb and span elements. At the end, li.addEventListener() will call the click handler.
Handling click events once the user selects a file:
const list = document.createElement(‘ul’);
list.setAttribute(‘class’, ‘fsp-picker–custom-source’);
const toUpload = [];
const handleClick = (e) => {
e.stopPropagation();
const element = e.currentTarget;
const idx = parseInt(element.dataset.idx);
const file = sourceUrlsArray[idx];
if (toUpload[idx]) {
element.classList.remove(‘file-selected’);
delete toUpload[idx];
} else {
element.classList.add(‘file-selected’);
toUpload[idx] = file;
}
return false;
};
From the segment above, we define the current element and its dataset index. Set the file constant equal to sourceUrlsArray[idx]. It checks if the file was marked for upload and moves it to the toUpload list. Otherwise, the file-selected class is removed and it’s deleted from the list. Unmarked files will receive the class with its toUpload index set to the file object.
And finally, you can display the summary view by adding them from the queue with a Promise.all(). Essentially, this HTML list contains all the attached files you want the user to view or edit. It improves the quality and efficiency of uploads, scaling them across many web apps.
What Is The Key Takeaway Of The Custom Source Plugin?
A JS file upload API saves time and money on content uploads by connecting external libraries and third-party packages with your browser apps on just about any device. All you need is a good understanding of HTML, CSS, and vanilla JS to construct your very own uploader.
Sign up now to build a custom source that works with your application.
Filestack is a dynamic team dedicated to revolutionizing file uploads and management for web and mobile applications. Our user-friendly API seamlessly integrates with major cloud services, offering developers a reliable and efficient file handling experience.