How to send a file using XMLHttpRequest
I'm developing a sailfish app in QML + javascript. Is there a way to send a file (image) to an endpoint using HTTP POST? Apparently QML javascript does not support FormData, which would have been a solution.
Currently I'm using something like this:
function api_post(callback, end_point, send_data, params) {
var xhr = new XMLHttpRequest();
params = params || {};
var parameters = "";
for (var p in params) {
parameters += "&" + p + "=" + params[p];
}
var request = api_url + end_point + "?personToken=" + person_token + "&access_token=" + access_token + parameters;
console.log(request)
send_data = JSON.stringify(send_data)
console.log(send_data)
xhr.onreadystatechange = function() {processRequest(xhr, callback);};
xhr.open('POST', request, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.setRequestHeader("Accept", "application/json");
xhr.send(send_data);
}
function processRequest(xhr, callback, e) {
if (xhr.readyState === 4) {
console.log(xhr.status)
var response
try {
response = JSON.parse(xhr.responseText);
}
catch (e) {
response = xhr.responseText
}
callback(xhr.status, response);
}
}
But this only works for text data.
This works for me. The code is used to control an IR LED strip via WiFi using a NodeMCU;
If there is a less clunky way of doing this, I'd like to see it :)
RELATED: https://together.jolla.com/question/16995/xmlhttprequest-responsetext-cutting-off-data/
Spam Hunter ( 2019-10-01 21:22:12 +0200 )editMy question is about how to send an image file from a sailfish app to a remote endpoint. I have already figured out how to handle text data (yeah, the same clunky way :) ), but not how to send a binary file.
tmy ( 2019-10-01 22:15:04 +0200 )editMy bad, speed reading again!
Spam Hunter ( 2019-10-02 12:34:56 +0200 )edit