Skip to content

Instantly share code, notes, and snippets.

@creesch
Created March 17, 2020 19:31
Show Gist options
  • Save creesch/d6b69bbd8d38b4b1ddb76dd774b9abc3 to your computer and use it in GitHub Desktop.
Save creesch/d6b69bbd8d38b4b1ddb76dd774b9abc3 to your computer and use it in GitHub Desktop.
'use strict';
const formData = require('form-data');
const axios = require('axios');
const chokidar = require('chokidar');
const notifier = require('node-notifier');
const clipboardy = require('clipboardy');
const path = require('path');
const os = require('os');
const fs = require('fs');
const imageUploadPath = path.resolve(os.homedir(), 'Pictures', 'Upload');
chokidar.watch(imageUploadPath).on('add', filePath => {
if (/.+?\..{2,5}$/.test(filePath)) {
uploadAndDelete(filePath);
}
});
function uploadAndDelete (filePath) {
const form = new formData();
form.append('fileToUpload', fs.createReadStream(filePath));
form.getLength((err, length) => {
if (err) {
notifier.notify({
title: 'Image uploader',
message: 'ERROR: Problem with upload attempt.',
});
console.error(err);
return;
}
const formHeaders = form.getHeaders();
formHeaders['Content-Length'] = length;
axios.post('URL', form, {
headers: formHeaders,
})
.then(response => {
clipboardy.writeSync(response.data.fileUrl);
notifier.notify({
title: 'Image uploader',
message: 'Image uploaded, url copied to clipboard.',
icon: filePath,
});
fs.unlink(filePath, err => {
if (err) {
console.error(err);
notifier.notify({
title: 'Image uploader',
message: 'Problem with file deletion.',
});
}
});
})
.catch(error => {
notifier.notify({
title: 'Image uploader',
message: 'ERROR: Problem with upload attempt request.',
});
console.error(error);
});
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment