I looked around stackoverflow and on google but didn't find a working solution so far.
I'm trying to send and image file via xmlhttp request to a server. I found this site: https://ptsv2.com/ to test the upload.
I get from the server a 200 - OK back when I send my request, but it shows me also that no files where uploaded (Files: 0)
this is my code:
var url = "https://corsanywhere.herokuapp.com/https://ptsv2.com/t/zuaco-1549007477/post";
var base64Credentials = btoa(username+":"+password);
var xhttp = new XMLHttpRequest();
var fd = new FormData();
/* Add the file */
fd.append("file", "img/1.png");
xhttp.open("POST", url, true);
xhttp.setRequestHeader("Authorization", "Basic " + base64Credentials);
xhttp.setRequestHeader("Content-Type", "image/png");
xhttp.send(fd);
/* Check the response status */
xhttp.onreadystatechange = function()
{
if (xhttp.readyState == 4 && xhttp.status == 200)
{
console.log("UPLOAD SUCCESSFUL: " + xhttp.statusText);
console.log("GET ALL: " + xhttp.getAllResponseHeaders());
}
else {
console.log("UPLOAD FAILED!")
}
}
For security reasons you cannot set manually a file. Instead use file input element:
var xhttp = new XMLHttpRequest();
var fd = new FormData();
// fd.append("file", "img/1.png");
fd.append("file", document.getElementById('yourInput').files[0]);
Related
I am trying to develop a component in Joomla 4. I have a simple button that should fire of a script to update the database.
I can make the call to the JavaScript ok, but the JavaScript does not appear to open the request URL, if anything it opens the current URL or refreshes the page. The script works fine outside of Joomla but not inside.
I have tried both the following, and the same thing happens:
*function buttonLike()
{
var xhr = new XMLHttpRequest();
var parentEl = this.parentElement;
//var url = 'index.php?com_reflect&format=raw;
var url = 'liked.php';
console.log('Get Here OK' + parentEl.id);
xhr.open('GET', 'liked.php', true);
// Form data is sent appropriately as a POST request
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.onreadystatechange = function ()
{
if(xhr.readyState == 4 && xhr.status == 200)
{
var result = xhr.responseText;
console.log('Never Here Result: ' + result);
}
if(xhr.readyState == 4 && xhr.status == 0)
{
console.log('Always Here');
}
};
xhr.send("id=" + parentEl.id);
}*
OR
function buttonLike()
{
//var url = 'index.php?com_reflect&format=raw;
var url = 'liked.php';
var request = new Ajax(url, {
method: 'post',
update: some_div,
data: options,
onComplete: function (){
$('some_field').setHTML('I am finished!');
}
}).request();
Been going round in circles on this one, any help would be appreciated.
I am trying to send file in folder using javascript and my code is proper working in local machine but when i have upload the project in server this this not working
var formdata = new FormData();
var fileInput = $("#fileInput")[0];
formdata.append(fileInput.files[0].name, fileInput.files[0]);
var xhr = new XMLHttpRequest();
xhr.open('POST', ControllerUrl+'Upload');
xhr.send(formdata);
xhr.onreadystatechange = function () { //This condition gone false and code is move ahead
if (xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText);
}
}
I need to send a HTML-Canvas image from a Webpage to a Servlet for Image Processing. On my webpage, this will be done by uploading a jpg or png image and then clicking a process button.
My frontend is working (I can upload and display images), but I do not know how to send an image from a webpage to a server and vice-versa.
Can you please help me?
HTML: (img stored in canvas)
<canvas id="canvas"></canvas>
JavaScript:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Ajax Code here???
}
};
xhttp.open("GET", ?, true);
xhttp.send();
Unfortunately, not all browsers does support Canvas.toBlob() function. For example MS Edge and other browsers does not support it (see browser compatibility). Because of this we have to use Canvas.toDataURL() function.
I wrote for you the solution which does the same like normal sending a form from HTML:
var canvas = document.getElementById('canvas'),
dataURL = canvas.toDataURL('image/jpeg', 0.7), //or canvas.toDataURL('image/png');
blob = dataURItoBlob(dataURL),
formData = new FormData(),
xhr = new XMLHttpRequest();
//We append the data to a form such that it will be uploaded as a file:
formData.append('canvasImage', blob);
//'canvasImage' is a form field name like in (see comment below).
xhr.open('POST', 'jsp-file-on-your-server.jsp');
xhr.send(formData);
//This is the same like sending with normal form:
//<form method="post" action="jsp-file-on-your-server.jsp" enctype="multipart/form-data">
// <input type="file" name="canvasImage"/>
//</form>
function dataURItoBlob(dataURI)
{
var aDataURIparts = dataURI.split(','),
binary = atob(aDataURIparts[1]),
mime = aDataURIparts[0].match(/:(.*?);/)[1],
array = [],
n = binary.length,
u8arr = new Uint8Array(n);
while(n--)
u8arr[n] = binary.charCodeAt(n);
return new Blob([u8arr], {type: mime})
}
If you do not know how to save files on server side using JSP, please read:
How to upload files on server folder using JSP
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var canvas = document.getElementById('canvas');
canvas.toBlob(function(blob) {
var oReq = new XMLHttpRequest();
oReq.open("POST", /*URL*/, true);
oReq.onload = function (oEvent) {
// Uploaded.
};
oReq.send(blob);
},'image/jpeg', 0.95);
}
};
xhttp.open("GET", ?, true);
xhttp.send();
More information:CanvasElement toBlob and Sending Blob
Thank you for reading!
I want to open a PDF from a REST backend that gets loaded via XHR in a new tab with specified filename and Authorization header.
So far I managed to download it with this (incl. auth headers and filename):
// saves XHR stream as file with configurable filename
downloadXHRFile:function(endpoint,data,method,filename,errorcallback,mimetype){
bsLoadingOverlayService.start();
var def = $q.defer();
var token = localStorageService.get('token');
var xhr = new XMLHttpRequest();
xhr.open(method, CONFIG.URL+endpoint, true);
xhr.setRequestHeader('Authorization', 'Bearer '+token);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.responseType = 'arraybuffer';
xhr.onload = function(e) {
if (this.status == 200) {
var blob=new Blob([this.response], {type:mimetype});
var link=document.createElement('a');
link.href=window.URL.createObjectURL(blob);
link.download=filename;
link.click();
bsLoadingOverlayService.stop();
}else{
bsLoadingOverlayService.stop();
errorcallback(xhr.statusText);
}
def.resolve();
};
xhr.send(
JSON.stringify(data)
);
return def;
},
Further I managed to open it in a new tab with the following code (incl. auth headers).
Unfortunately the URL (and by that the filename) looks like this:
blob:http://localhost:3000/0857f080-d152-48c6-b5fb-6e56292db651
Probably it can be solved somehow like above but I cant find the solution.
Does someone have a clever idea how I could set the filename in the new Tab?
// opens XHR filestream in tab
openXHRFile: function(endpoint,filename,errorcallback){
var token = localStorageService.get('token');
var our_url = CONFIG.URL+endpoint;
var win = window.open('_blank');
downloadFile(our_url, function(blob) {
var url = URL.createObjectURL(blob);
win.location = url;
});
function downloadFile(url, success) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.setRequestHeader("Authorization", 'Bearer '+token);
// xhr.setRequestHeader('Content-Type', 'application/json');
xhr.responseType = "blob";
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (success) success(xhr.response);
}else{
}
};
xhr.send(null);
}
},
How can I test user credentials using javascript?
I tested the good URL with app_code and app_id. When they are ok all other requests seem to be ok too.
You can do it so e.g.:
var app_id = "test_app_id";
var app_code = "test_app_code";
var xhr = new XMLHttpRequest();
xhr.addEventListener("readystatechange", function () {
if (this.readyState === 4 ) {
if(this.responseText.indexOf("France") != -1){
console.log("Credentials is OK");
}else{console.log("Wrong credentials");}
}
});
xhr.open("GET", "https://geocoder.api.here.com/6.2/geocode.json?app_id="+ app_id+"&app_code=" + app_code + "&country=FRA");
xhr.send();