Settings
- Node.js v18.14.0
- axios v1.3.5
file.service.ts
import { AxiosInstance, AxiosRequestConfig } from 'axios';
import { createReadStream, createWriteStream } from 'fs';
import { dirname, join as joinPath } from 'path';
import FormData from 'form-data';
// import { randomString } from 'YOUR_RANDOM_STRING_GENERATOR';
export class FileService {
constructor(private readonly axios: AxiosInstance) {}
getExtensionFromUrl(url: string) {
return url.split(/[#?]/)[0].split('.').pop().trim();
}
/**
* @return saved local image path
*/
downloadFile(saveDir: string, url: string): Promise<string> {
return new Promise(async (resolve, reject) => {
const response = await this.axios.get(url, { responseType: 'stream' });
const extension = this.getExtensionFromUrl(url);
const filename = `${randomString()}.${extension}`;
const savedFilePath = joinPath(dirname(saveDir), filename);
const writer = createWriteStream(savedFilePath);
response.data.pipe(writer);
writer.on('error', reject);
writer.on('close', () => resolve(savedFilePath));
});
}
/**
* @param url request url
* @param filePath local file path
*/
uploadFile(url: string, filePath: string) {
const formdata = new FormData();
formdata.append('file', createReadStream(filePath));
const config: AxiosRequestConfig = {
headers: {
'Content-Type': `multipart/form-data; boundary=${formdata.getBoundary()}`,
},
};
return this.axios.post(url, formdata, config);
}
}