Skip to content

Instantly share code, notes, and snippets.

@lechuhuuha
Created June 12, 2024 07:43
Show Gist options
  • Save lechuhuuha/942a8973c555d9385984dca8ac5639f7 to your computer and use it in GitHub Desktop.
Save lechuhuuha/942a8973c555d9385984dca8ac5639f7 to your computer and use it in GitHub Desktop.
upload file from read stream
import fs from 'fs';
import path from 'path';
import axios from 'axios';
import FormData from 'form-data';
// Path to the file you want to upload
const filePath: string = path.join(__dirname, 'yourfile.txt');
// URL of the remote server
const url: string = 'https://example.com/upload';
// Create a new FormData instance
const form = new FormData();
// Append the file to the form data
form.append('file', fs.createReadStream(filePath));
// Function to upload the file
async function uploadFile(): Promise<void> {
try {
// Make the POST request with axios
const response = await axios.post(url, form, {
headers: {
// Spread the form headers to set the correct Content-Type and boundary
...form.getHeaders()
}
});
console.log('File uploaded successfully', response.data);
} catch (error) {
console.error('Error uploading file', error);
}
}
// Call the upload function
uploadFile();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment