get images from api and save to b2 in typescript

To get images from an API and save them to B2 cloud storage in TypeScript, you will need to do the following:

  1. Install the required dependencies using npm or yarn. You will need node-fetch to fetch the image from the API and fs-extra to write the file to disk and upload it to B2 cloud storage.
index.ts
npm install node-fetch fs-extra
32 chars
2 lines
  1. Make a request to the API to get the image data using node-fetch. The response will be a Buffer object containing the binary image data.
index.ts
import fetch from 'node-fetch';

const response = await fetch('https://example.com/image.jpg');
const imageData = await response.buffer();
139 chars
5 lines
  1. Write the image data to a file on disk using fs-extra.
index.ts
import fs from 'fs-extra';

await fs.outputFile('/path/to/image.jpg', imageData);
82 chars
4 lines
  1. Upload the file to B2 cloud storage. You will need to have a B2 account and obtain an account ID and an application key.
index.ts
import { B2 } from 'backblaze-b2';

const b2 = new B2({
  accountId: 'your-account-id',
  applicationKey: 'your-application-key'
});

await b2.authorize();

// Get the bucket ID for your bucket
const bucketId = await b2.getBucketId({ bucketName: 'your-bucket-name' });

// Upload the file to your bucket
const fileName = 'image.jpg';
const fileData = await fs.readFile('/path/to/image.jpg');
const fileStats = await fs.stat('/path/to/image.jpg');
const uploadUrl = await b2.getUploadUrl({ bucketId });
const fileInfo = await b2.uploadFile({
  uploadUrl: uploadUrl.uploadUrl!,
  uploadAuthToken: uploadUrl.authorizationToken!,
  fileName,
  fileData,
  fileSize: fileStats.size
});
681 chars
25 lines

This should upload the file to your B2 cloud storage bucket. You can also add more options to the uploadFile method, such as setting custom metadata or file retention settings. Check the backblaze-b2 documentation for more information.

gistlibby LogSnag