How can I convert the following javascript based on XMLHttpRequest to Fetch?
This is the sample code provided by Trix-editor for uploading images from here
I want to migrate to Fetch for a few reasons:
-
I want to be consistent across my codebase and use
fetch()
for my other API calls. -
I’m a newbie and read the XMLHttpRequest doc but don’t understand it. Fetch just seems more intuitive to me for some reason so another reason to convert this.
-
Plus, this code does not work for me but I don’t know how to
troubleshoot. I have a Flask route that uploads the file (the one specified as HOST) but the tags aren’t being saved in Trix-editor.(function() {
var HOST = “http://localhost:5000/_upload/”addEventListener(“trix-attachment-add”, function(event) {
if (event.attachment.file) {
uploadFileAttachment(event.attachment)
}
})function uploadFileAttachment(attachment) {
uploadFile(attachment.file, setProgress, setAttributes)function setProgress(progress) { attachment.setUploadProgress(progress) } function setAttributes(attributes) { attachment.setAttributes(attributes) }
}
function uploadFile(file, progressCallback, successCallback) {
var key = createStorageKey(file)
var formData = createFormData(key, file)
var xhr = new XMLHttpRequest()
xhr.open(“POST”, HOST, true)xhr.upload.addEventListener("progress", function(event) { var progress = event.loaded / event.total * 100 progressCallback(progress) }) xhr.addEventListener("load", function(event) { if (xhr.status == 204) { var attributes = { url: HOST + key, href: HOST + key + "?content-disposition=attachment" } successCallback(attributes) } }) xhr.send(formData)
}
function createStorageKey(file) {
var date = new Date()
var day = date.toISOString().slice(0,10)
var name = date.getTime() + “-” + file.name
return [ “tmp”, day, name ].join(“/”)
}function createFormData(key, file) {
var data = new FormData()
data.append(“key”, key)
data.append(“Content-Type”, file.type)
data.append(“file”, file)
return data
}
})();