Created
March 17, 2020 19:31
-
-
Save creesch/d6b69bbd8d38b4b1ddb76dd774b9abc3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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