How to Upload Files to Backblaze B2
How do you upload files and photos via a Firebase Google Deject Function to a Backblaze B2 storage bucket?
Introduction
In this commodity I show you how you can receive files and images trough a serverless Firebase Deject Function, process them and then stores the files in a Backblaze B2 bucket.
This function tin can be used, for example, to upload profile pictures or download information. The sender can be a simple HTML form on a website or an upload function in an APP.
Why Firebase Cloud Functions?
Cloud Functions allow to execute Javascript code in the backend without the need to run a server. Not merely practise yous salvage a lot of setup time for a server, but you also don't have to worry about the security and assistants of the server. The same applies to the storage of data in a bucket, but of course y'all should still pay attending to the security and accessibility.
Another reward of a serverless function is the scalability. Cloud functions are only active when they are addressed. Different a normal server, which must ever be active and accessible. Cloud Functions tin therefore wonderfully intercept load peaks and only pay for the actual use.
Why Backblaze B2
Why should y'all utilise Backblaze B2 and non the Google Cloud Storage already integrated in Firebase? Price!
Backblaze is a US-American company that became famous for its backup software. Similar to Amazon, they decided to make the engineering science to run this service available to others.
Currently, one gigabyte of storage at Backblaze costs $0.005 per month. With Google Firebase information technology is 0.026 US dollars per GB, which is near 5 times the price of Backblaze B2.
The traffic for the upload is free with both providers. Per ten,000 upload operations, nonetheless, Firebase charges $0.004. In that location is no charge for the API upload call, simply the transaction for authentication (b2_authorize_account) is charged. Per x,000 requests this is $0.04.
Download traffic is charged at $0.01 (Backblaze) and $0.12 (Firebase) per gigabyte. In addition, there is $0.004 per 10,000 API requests.
All the same, Backblaze has a free tier of ii,500 API calls and 1 GB traffic per twenty-four hour period. In add-on, there is 10 GB of storage per month for free.
Firebase also comes with an allowance. The Spark Plan includes 5 GB storage, i GB download traffic per day and 20,000 download calls and l,000 download calls per day.
The pure storage costs for 100 GB are therefore $0.45 (Backblaze) and $two,47 (Firebase). By the fashion, the costs for storage at Amazon S3 would be in the range of Firebase.
Before y'all decide on 1 of the providers, you should calculate exactly which one makes the most sense for you.
The current prices can be found on the website of Backblaze and Firebase.
Setup
Of grade you should have an business relationship with Backblaze and Firebase. Furthermore, the commandline-tool of Firebase should be installed.
An important bespeak with Firebase is that the billing plan is set up from Spark to Bonfire. This is the only mode to enable connections outside of the Google Cloud.
Backblaze API Keys
For authentication we demand an API key from Backblaze. The Master Central can be used for this. For security reasons, however, y'all should create a special fundamental for this function. This is hands done on the website under "App Keys". Here you lot can limit the access to merely one specific bucket.
After creating the key, note down the keyID and the applicationKey. We need these later. Likewise needed is the BucketID. This ID tin can exist found in the info menu on the overview page of the buckets.
Calculation a new API central
Bucket ID
The ii needed values
Code
The code for this function is actually quite simple and can be easily extended if necessary.
The node.js module "busboy" parses the HTML Grade Data and writes the incoming file into the temporary storage of the cloud function. Later on the authentication of B2 takes place and the file is written to the specified bucket.
In the following I will go through some important parts of the Cloud Function. You can notice the complete code on Github.
This is probably the almost of import function of the function. Hither you have to provide API data from Backblaze.
// Initiate B2 with auth keys const b2 = new b2CloudStorage({ auth: { accountId: "<keyId>", // The unique keyID to the cardinal applicationKey: "<applicationKey>", }, }); const B2bucketId = "";
In this part the proper name of the file is divers. As an instance, nosotros will simply use a random combination of numbers here. Of course you can hands employ your own scheme.
// Get file extension const fileExtension = filename.split(".")[filename.split(".").length - ane]; // Select filename / Random number with file extension newFileName = `${Math.round(Math.random() * 1000000000000).toString()}.${fileExtension}`;
This part is responsible for uploading the file. If you want to sort the file into a specific directory, y'all accept to exercise this in this part.
b2.uploadFile(tempFile.filepath, { bucketId: B2bucketId, fileName: tempFile.newFileName, // Upload to a directory // fileName: "userfiles/" + thumbFileName, contentType: tempFile.mimetype, },
After the successful upload, this example returns a simple HTTP response. Of course you could integrate other deportment here. For example salve the data in the Firestore database or send back the filename.
If you want to compare the saved version with the temporary file once more, this is also possible. In response Backblaze also sends the MD5 and SHA1 hash.
function (err, results) { if (err) return res.status(500).json({ fault: err }); render res.status(201).json({ message: "File uploaded!" }); }
In the complete lawmaking there is also a special function for the upload. This part checks whether an paradigm is involved using the MIME type. If this is not the instance, it sends an fault to the requestor.
if ( mimetype !== "image/jpeg" && mimetype !== "image/png" && mimetype !== "image/gif" ) { return res.condition(400).json({ error: "Wrong file type", }); }
Extras
Of grade this function tin can however be extended and adapted in many aspects. And then it is also possible to use another event every bit trigger. For case, when creating a file in Firebase Storage, the file can be saved direct on Backblaze as a backup.
Environment variables
The API cardinal and the saucepan ID should not be stored directly in the lawmaking if possible. For this you tin can use the environment variables of Firebase.
You have to run this code, with the appropriate values, on the command line.
firebase functions:config:gear up b2.keyid="{keyId}" b2.appkey="{applicationKey}" b2.bucketid="{BucketID}"
The values can then be requested up accordingly.
const b2 = new B2({ auth: { accountId: functions.config().b2.keyid, applicationKey: functions.config().b2.appkey, }, }); const B2bucketId = functions.config().b2.bucketid;
Select region
Both Firebase and Backblaze offering distribution and storage in different regions of the globe.
Reasons for the pick can be price (in this case information technology makes no difference) or jurisdiction and requirements. In almost cases, however, the underlying idea will be speed.
If possible, the storage location should be close to your target audience.
Backblaze currently offers but two locations. US West, where the data is located in Sacramento (California) and Phoenix (Arizona) and EU Central, with Amsterdam as the location.
With Google Firebase y'all have some more options. At the moment yous tin can cull between united states-central1 (Iowa), united states-east1 (Due south Carolina), us-east4 (Northern Virginia), europe-west1 (Belgium), europe-west2 (London), europe-west3 (Frankfurt), asia-east2 (Hong Kong) and asia-northeast1 (Tokyo).
The selected region is indicated direct in the code. For Frankfurt, for case, this would be this section.
exports.uploadFile = functions.region("europe-west1").https.onRequest((req, res) => {
Of course, one should not but consider the proximity of the cloud function to the visitors, but also to the Backblaze B2 Saucepan. Depending on the location, there might be a higher upload latency.
Resize images
If you work with images, you will probably want to procedure them before uploading. For this you lot tin can use the Node.js module "sharp". This module can easily enlarge and reduce image files in all desired sizes. If you want, yous tin can too catechumen the paradigm into some other format like WebP.
Download
Y'all can discover the complete lawmaking for free on Github.
Source: https://viarami.com/programming/backblaze-b2-firebase-cloud-functions/
0 Response to "How to Upload Files to Backblaze B2"
Post a Comment