XMLHttpRequest detecting 404 (Not Found) - javascript

If the URL is correct (file.dat exists), this works great (the file length matches). If it is wrong I will see a very small file length and I will not see the xhr.onerror.
How can I detect that the URL was incorrect?
var xhr = new XMLHttpRequest()
xhr.responseType = "blob"
xhr.onload = ()=> {
var reader = new FileReader()
reader.onload = evt => {
var contents = new Buffer(evt.target.result, 'binary')
console.log('file len',contents.length)
}
reader.readAsBinaryString(xhr.response)
}
xhr.addEventListener("error", () => { console.error('xhr.onerror',e) })
xhr.open("GET", "file.dat")
xhr.send()
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest
I do see a stacktrace in the console pointing to xhr.send()
GET http://localhost:8080/file.dat 404 (Not Found)
A try catch around both open and send does not catch any exceptions.
Files are served by WebpackDevServer (I hope that should not matter though).

You can check the status of the response object.
// Not using arrow function because I don't want the lexical `this`
xhr.onload = function() {
if (this.status === 404) {
// not found, add some error handling
return;
}
var reader = new FileReader()
reader.onload = evt => {
var contents = new Buffer(evt.target.result, 'binary')
console.log('file len',contents.length)
}
reader.readAsBinaryString(xhr.response)
}
Credit to https://developer.appcelerator.com/question/129410/xhr-request-cant-check-for-error-for-404-page-or-other-errors

Using https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#xmlhttprequest-status:
XmlHttpRequest objects (you have one in the variable xhr) have a read-only property status that you can use to get the status text once it's loaded.

Related

Download mp3 file from url with xmlHttpRequest and writing it to file

I've currently tried every possible ways to do this but I cannot get it to work, despite reading every related question on the internet ...
I'm simply trying to download an mp3 arrayBuffer that i GET from an url with the module xmlHttpRequest from my node server code with the intent to then writing the buffer to an mp3 file, here is the code:
const endpoint = "https://cdns-preview-a.dzcdn.net/stream/c-ae4124ee0e63b9f6abffddb36b9695cf-2.mp3";
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var oReq = new XMLHttpRequest();
oReq.open("GET", endpoint, true);
oReq.responseType = "arraybuffer";
oReq.onload = function (oEvent) {
if (this.status != 200) {
console.log(this.status)
}
console.log(oReq.response);
var uInt8Array = new Uint8Array(oReq.response);
console.log(uInt8Array);
var dest = "1.mp3";
var stream = fs.createWriteStream(dest);
stream.write(uInt8Array);
stream.end();
}
};
oReq.send();
oReq.response is always empty, no matter what I type in oReq.responseType(arraybuffer, blob).
if I try to write oReq.responseText, it's always going to be some scuffed encoding because it was translated to text.
Can you give me advices, is there some underlying deep layer that I don't understand, is it possible to do what I wanna achieve?
Found a solution with http get instead of xmlHttpRequest:
const endpointe = "https://cdns-preview-a.dzcdn.net/stream/c-ae4124ee0e63b9f6abffddb36b9695cf-2.mp3";
https.get(endpointe, (res) => {
datatest = []
res.on('data', function(chunk) {
datatest.push(chunk);
console.log(chunk);
});
// The whole response has been received. Print out the result.
res.on('end', () => {
//console.log(data)
var dest = "test.mp3";
var stream = fs.createWriteStream(dest);
var buffer = Buffer.concat(datatest);
stream.write(buffer);
stream.end();
});
}).on('error', (e) => {
console.error(e);
});

Problem grabbing image from server with https request in PlayCanvas

I'm trying to use the PlayCanvas OAuth and CORS to request an image from a service via HTML request. as I understood the response return a JSON holding the data, and in this question I just want to save the path in the JSON to a .txt file located in the PlayCanvas Assets.
I'm not 100% sure about my code.
I haven't found how to grab the .txt into the JS script (it cannot be attached to an object)
will appreciate help with both
URL is
https://s3-us-west-2.amazonaws.com/ticomsoft-image-repo/1.png
I've tried to use an async request like the example appearing here
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests
in the 'createCORSRequest':
if ("withCredentials" in xhr) {
// Check if the XMLHttpRequest object has a "withCredentials" property.
// "withCredentials" only exists on XMLHTTPRequest2 objects.
xhr.open(method, url, true);
xhr.onload = function (e) {
if (xhr.readyState === 46) {
if (xhr.status === 200) {
console.log(xhr.responseText);
} else {
console.error(xhr.statusText);
}
}
};
xhr.onerror = function (e) {
console.error(xhr.statusText);
};
I tried to place the 'stringify' and 'download' commands in initialize (moved then inside the callback
and finally ended up with what's appearing here
var Https = pc.createScript('https');
var token = 'That's the PlayCanvas Token';
var request = 'curl -H "Authorization: Bearer '+token+'" ';
var ts_URL ='https://s3-us-west-2.amazonaws.com/ticomsoft-image-repo/1.png';
// initialize code called once per entity
Https.prototype.initialize = function() {
var url = request+ts_URL;
// ref: curl -H "Authorization: Bearer nesgdxhiqe7hylfilr6ss1rds0gq1uj8" https://playcanvas.com/api/...
var xhr = createCORSRequest('GET', url);
if (!xhr) {
throw new Error('CORS not supported');
}
};
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// Check if the XMLHttpRequest object has a "withCredentials" property.
// "withCredentials" only exists on XMLHTTPRequest2 objects.
if(method=="GET")
{
loadFile(url, DownloadToText(xhr));
}
// else... all the other cases
return xhr;
}
function loadFile(url, callback /*, opt_arg1, opt_arg2, ... */) {
var xhr = new XMLHttpRequest();
xhr.callback = callback;
xhr.arguments = Array.prototype.slice.call(arguments, 2);
xhr.onload = xhrSuccess;
xhr.onerror = xhrError;
xhr.open("GET", url, true);
xhr.send(null);
}
function DownloadToText (ans)
{
JSON.stringify(ans);
download(ans, 'json.txt', 'text/plain');
}
function download(content, fileName, contentType) {
var a = document.createElement("a");
var file = new Blob([content], {type: contentType});
a.href = URL.createObjectURL(file);
a.download = fileName;
a.click();
}
function xhrSuccess() {
this.callback.apply(this, this.arguments);
}
function xhrError() {
console.error(this.statusText);
}
expected results: I expected a json.txt file to be downloaded with the URL of the image inside.
Actual results: when I launched the program and went to console, saw the image 1.png got a 404 Not Found error.
the json.txt was downloaded with '[object XMLHttpRequest]'.
Also
in the F12 i got that the link leading to the error is
https://launch.playcanvas.com/curl%20-H%20%22Authorization:%20Bearer%---theToken---%22%20https://s3-us-west-2.amazonaws.com/ticomsoft-image-repo/1.png
while simply
https://s3-us-west-2.amazonaws.com/ticomsoft-image-repo/1.png leads to the image.
but i can't get away from the prefix if i wanna pass through the OAuth.. which is why i don't understand what was i'm doing wrong.

Angular JS with PDFTron

I am trying to get a blob as a URL but i get an error on this line :
xhr.send()
The error message is angular.js:13920 Error: Failed to execute 'send' on 'XMLHttpRequest': The object's state must be OPENED.
But in the code I am using xhr.open('GET', blobValue) as shown in my code here
if(someBlobValue){
var viewerElement = $document[0].getElementById('viewer');
var myWebViewer = new PDFTron.WebViewer({
path: 'lib',
pdftronServer: 'https://demo.pdftron.com' // remove
}, viewerElement);
var xhr = new XMLHttpRequest;
xhr.responseType = 'blob';
xhr.onload = function() {
var recoveredBlob = xhr.response;
var reader = new FileReader;
reader.readAsDataURL(recoveredBlob);
};
xhr.open('GET', someBlobValue);
xhr.setRequestHeader('Content-type', 'application/pdf');
xhr.send(); //error here although its open?
//var file = new File([newValue], 'somefile.pdf');
myWebViewer.loadDocument(xhr.response, { filename: 'somefile.pdf'});
Currently i have the document as a blob but i am trying to load it to pdftron library and unfortunately i dont seem to find the myWebViewer.getInstance().loadLocalFile method in the DOM (its undefined).
Would appreciate any pointers as its the first time trying to use pdftron in the angularjs app.
NOTE : This is inside a directive.
You need to wait for the DOM element containing WebViewer to trigger the ready event, for the ReaderControl instance, returned from getInstance(), to be defined.
For example:
$(viewerElement).on('ready', function() {
myWebViewer.getInstance().loadLocalFile(someBlobValue);
});
There is nothing wrong in your code logically,
You just forgot to instantiate the XHR object over here var xhr = new XMLHttpRequest;.
You can correct it by doing this var xhr = new XMLHttpRequest();

Getting blob gives 404 error

could someone prompt me - how to save "blob in memory" to a file using Java Script?
e.g. I have in the page next blob-image:
<img src="blob:https%3A//drive.google.com/851b979c-92e9-4ef2-9152-8935f7793630" class="g-img">
and I need to save this blob to a file (png/jpg).
The next code just gives:
GET blob:https%3A//drive.google.com/851b979c-92e9-4ef2-9152-8935f7793630 404 (Not Found)
so it seems, usual way to get the blobs doesn't work here.
Is there any workaround to save this blob-images from browser memory to a file, or, saying more exactly - to get them as a real blob using only "src" tag value?
Thank you.
var srcEl = evt.srcElement;
var CurI = document.getElementsByClassName('g-img');
[].forEach.call(CurI, function (el) {
var xhr = new XMLHttpRequest();
xhr.open('GET', el.src, true);
xhr.responseType = 'arraybuffer'; // xhr.responseType = 'blob';
xhr.onload = function(e) {
if (this.status == 200) {
var myBlob = this.response;
var reader = new window.FileReader();
reader.readAsDataURL(myBlob);
console.log(myBlob);
}
};
xhr.send();
console.log(el.src);
// saveAs(myBlob, 'my2image.png');
}
p.s. to use mediarecorder?

how to find out if XMLHttpRequest.send() worked

I am using XMLHttpRequest to send a file from javascript code to a django view.I need to detect,whether the file has been sent or if some error occurred.I used jquery to write the following javascript.
Ideally I would like to show the user an error message that the file was not uploaded.Is there some way to do this in javascript?
I tried to do this by returning a success/failure message from django view , putting the success/failed message as json and sending back the serialized json from the django view.For this,I made the xhr.open() non-asynchronous. I tried to print the xmlhttpRequest object's responseText .The console.log(xhr.responseText) shows
response= {"message": "success"}
What I am wondering is,whether this is the proper way to do this.In many articles,I found the warning that
Using async=false is not recommended
So,is there any way to find out whether the file has been sent,while keeping xhr.open() asynchronous?
$(document).ready(function(){
$(document).on('change', '#fselect', function(e){
e.preventDefault();
sendFile();
});
});
function sendFile(){
var form = $('#fileform').get(0);
var formData = new FormData(form);
var file = $('#fselect').get(0).files[0];
var xhr = new XMLHttpRequest();
formData.append('myfile', file);
xhr.open('POST', 'uploadfile/', false);
xhr.send(formData);
console.log('response=',xhr.responseText);
}
My django view extracts file from form data and writes to a destination folder.
def store_uploaded_file(request):
message='failed'
to_return = {}
if (request.method == 'POST'):
if request.FILES.has_key('myfile'):
file = request.FILES['myfile']
with open('/uploadpath/%s' % file.name, 'wb+') as dest:
for chunk in file.chunks():
dest.write(chunk)
message="success"
to_return['message']= message
serialized = simplejson.dumps(to_return)
if store_message == "success":
return HttpResponse(serialized, mimetype="application/json")
else:
return HttpResponseServerError(serialized, mimetype="application/json")
EDIT:
I got this working with the help of #FabrícioMatté
xhr.onreadystatechange=function(){
if (xhr.readyState==4 && xhr.status==200){
console.log('xhr.readyState=',xhr.readyState);
console.log('xhr.status=',xhr.status);
console.log('response=',xhr.responseText);
var data = $.parseJSON(xhr.responseText);
var uploadResult = data['message']
console.log('uploadResult=',uploadResult);
if (uploadResult=='failure'){
console.log('failed to upload file');
displayError('failed to upload');
}else if (uploadResult=='success'){
console.log('successfully uploaded file');
}
}
}
Something like the following code should do the job:
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState === 4) {
var response = JSON.parse(xmlhttp.responseText);
if (xmlhttp.status === 200) {
console.log('successful');
} else {
console.log('failed');
}
}
}
XMLHttpRequest objects contain the status and readyState properties, which you can test in the xhr.onreadystatechange event to check if your request was successful.
XMLHttpRequest provides the ability to listen to various events that can occur while the request is being processed. This includes periodic progress notifications, error notifications, and so forth.
So:
function sendFile() {
var form = $('#fileform').get(0);
var formData = new FormData(form);
var file = $('#fselect').get(0).files[0]
var xhr = new XMLHttpRequest();
formData.append('myfile', file);
xhr.open('POST', 'uploadfile/', false);
xhr.addEventListener("load", transferComplete);
xhr.addEventListener("error", transferFailed);
}
function transferComplete(evt) {
console.log("The transfer is complete.");
// Do something
}
function transferFailed(evt) {
console.log("An error occurred while transferring the file.");
// Do something
}
You can read more about Using XMLHttpRequest.

Categories

Resources