First we need a function to upload the file to imgur:
/**
* Takes a file and uploads it to imgur.
*
* @param {File} file
* @return {Promise}
*/
function imgurUpload(file) {
var headers = new Headers({
'authorization': 'Client-ID <your imgur client ID>'
});
var form = new FormData();
form.append('image', file);
return fetch('https://api.imgur.com/3/image', {
method: 'post',
headers: headers,
body: form
}).then(function (response) {
return response.json();
}).then(function (result) {
if (result.success) {
return result.data.link;
}
throw 'Upload error';
});
}
Then the drag and drop plugin options:
var dragdropOptions = {
// The allowed mime types that can be dropped on the editor
allowedTypes: ['image/jpeg', 'image/png'],
handleFile: function (file, createPlaceholder) {
var placeholder = createPlaceholder();
imgurUpload(file).then(function (url) {
// Replace the placeholder with the image HTML
placeholder.insert('<img src=\'' + url + '\' />');
}).catch(function () {
// Error so remove the placeholder
placeholder.cancel();
alert('Problem uploading image to imgur.');
});
}
};
Finally create the editor with the options:
// Create the SCEditor instance with the dragdrop options
var textarea = ...;
sceditor.create(textarea, {
// Enable the drag and drop plugin
plugins: 'dragdrop',
// Set the drag and drop plugin options
dragdrop: dragdropOptions,
// Rest of SCEditor options
format: 'bbcode',
icons: 'monocons',
autofocus: true,
style: 'themes/content/default.css'
});
Done! The editor will now support uploading images to imgur.