Give a HTTP Filesystem API which accepts
GET /storage/filename
PUT /storage/filename
Request body: the file contents
and these headers
Content-Length: ...
Content-Type: application/octet-stream
How can one build a backbone.js File Model which works with it? (e.g. get file contents in a variable, put back updated contents)
If backbone.js doesn't support this, how would jQuery ajax requests look like?
While I haven't found support in jQuery/backbone, here's how it can be done:
var xhr = new XMLHttpRequest();
xhr.open('GET', "url", true);
xhr.setRequestHeader("Authorization", token);
xhr.responseType = "text";
xhr.onload = function(e) {
if (this.status == 200) {
var contents = this.response;
console.log("RECEIVED " + contents);
}
};
xhr.send();
More details at http://www.html5rocks.com/en/tutorials/file/xhr2/
Related
I followed this article to connect to Azure via Rest where the first step is to get an access-token for the service. So i tried to send the following request:
POST https://wamsprodglobal001acs.accesscontrol.windows.net/v2/OAuth2-13 HTTP/1.1
Content-Type: application/x-www-form-urlencoded
Host: wamsprodglobal001acs.accesscontrol.windows.net
Content-Length: 120
Expect: 100-continue
Connection: Keep-Alive
Accept: application/json
grant_type=client_credentials&client_id=ams_account_name&client_secret=URL_encoded_ams_account_key&scope=urn%3aWindowsAzureMediaServices
and replaced the client_id and key(encoded) in the data to be posted.
But Chrome promptly complains about setting the unsafe Host-, Content-Length-, Connection- and Expect-Headers. So i omitted those and end up with the following:
xhr = new XMLHttpRequest();
xhr.open("POST", "https://wamsprodglobal001acs.accesscontrol.windows.net/v2/OAuth2-13");
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Accept", "application/json");
xhr.send("grant_type=client_credentials&client_id=<id>&client_secret=<encodedSecret>scope=urn%3aWindowsAzureMediaServices");
now upon sending the request i get:
XMLHttpRequest cannot load https://wamsprodglobal001acs.accesscontrol.windows.net/v2/OAuth2-13. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://nope.com' is therefore not allowed access.
But the request works when i send it through the Rest Client, Fiddler and requestmaker.com which i take as evidence that the request is formed correctly ...
Any hint as to how i can get this to work would be greatly appreciated.
Try the following (generated from POSTMAN)
var data = "grant_type=client_credentials&client_id=<ACOUNTNAME>&client_secret=<ACCOUNTKEY>&scope=urn%3AWindowsAzureMediaServices";
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
if (this.readyState === 4) {
console.log(this.responseText);
}
});
xhr.open("POST", "https://wamsprodglobal001acs.accesscontrol.windows.net/v2/OAuth2-13");
xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("host", "wamsprodglobal001acs.accesscontrol.windows.net");
xhr.setRequestHeader("connection", "Keep-Alive");
xhr.setRequestHeader("accept", "application/json");
xhr.setRequestHeader("cache-control", "no-cache");
xhr.send(data);
In Postman, i have to have the Interceptor plugin enabled for this to work though, and disable Automatically Follow Redirects. See if that helps at all.
After you get the response back and parsed the access_token, you can use it in the next call to get the closest API endpoint like this
var data = null;
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
if (this.readyState === 4) {
console.log(this.responseText);
}
});
xhr.open("GET", "https://media.windows.net/");
xhr.setRequestHeader("x-ms-version", "2.11");
xhr.setRequestHeader("authorization", "Bearer <ACCESS_TOKEN>");
xhr.setRequestHeader("cache-control", "no-cache");
xhr.send(data);
I'm sending chunked data from a NodeJS application back to the browser. The chunks are really json strings. Problem I'm having is that every time the onprogress function is called, it adds on a string of the complete data. Meaning that response chunk number two, is appended to response chunk number one, and so on. I'd like to get ONLY the "just now" received chunk.
Here's the code:
console.log("Start scan...");
var xhr = new XMLHttpRequest();
xhr.responseType = "text";
xhr.open("GET", "/servers/scan", true);
xhr.onprogress = function () {
console.log("PROGRESS:", xhr.responseText);
}
xhr.send();
So really, the contents of xhr.responseText contains, when the third response comes, also the response text for the first and the second response. I've checked what the server is sending, and it doesn't look like there's a problem there. Using Node with Express, and sending with res.send("...") a couple of times. Also headers are set like so:
res.setHeader('Transfer-Encoding', 'chunked');
res.setHeader('X-Content-Type-Options', 'nosniff');
res.set('Content-Type', 'text/json');
This index based approach works for me:
var last_index = 0;
var xhr = new XMLHttpRequest();
xhr.open("GET", "/servers/scan");
xhr.onprogress = function () {
var curr_index = xhr.responseText.length;
if (last_index == curr_index) return;
var s = xhr.responseText.substring(last_index, curr_index);
last_index = curr_index;
console.log("PROGRESS:", s);
};
xhr.send();
Inspired by https://friendlybit.com/js/partial-xmlhttprequest-responses/
I am trying to upload a image to server,In that i have converted image to base64encode string and i need to pass that base64encode string to webservice,that webservice convert the base64 string to file and saving in database.but base64encode string has huge length approximately(85,000) when i pass this string to webservice i am getting the following error.
Failed to load resource: the server responded with a status of 400 (Bad Request)
i need to pass this by using only XMLHttpRequest() with out using the ajax,jquery please help me.
below is my code.
var filesToBeUploaded = document.getElementById("afile");
var file = filesToBeUploaded.files[0];
var reader = new FileReader();
reader.onload = function(event) {
var binaryStringResult = reader.result;
var binaryString =binaryStringResult.split(',')[1];
var xhr = new XMLHttpRequest();
xhr.open("POST","http://url/api/jsonws/Global-portlet.org_roles/add-file-entry?repositoryId=11304&folderId=0&sourceFileName=test108.jpeg&mimeType=image%2Fjpeg&title=test108.jpeg&description=test108.jpeg&changeLog=test108.jpeg&basecode64="+ binaryString);
xhr.setRequestHeader("Authorization","BasicbmFyYXlhbmFAdmlkeWF5dWcuY29tOnRlc3Q=");
xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded');
xhr.send();
xhr.onload = function() {
alert('in sucess');
};
xhr.onerror = function(e) {
alert('in error');
};
}
reader.readAsDataURL(file);
For POST, don't include it in the URL, you need to put it in the body, i.e.
xhr.send(binaryString);
I doubt your Content-Type of application/x-www-form-urlencoded is correct in this case.
I think the issue that you encountering here is that you are exceeding the maximum length of a query string.
What you need to do is something like the following:
var xhr = new XMLHttpRequest();
var url = "http://url/api/jsonws/Global-portlet.org_roles/add-file-entry";
var params = "repositoryId=11304&folderId=0&sourceFileName=test108.jpeg&mimeType=image%2Fjpeg&title=test108.jpeg&description=test108.jpeg&changeLog=test108.jpeg&basecode64="+ binaryString;
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Content-length", params.length);
xhr.setRequestHeader("Connection", "close");
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText);
}
}
xhr.send(params);
Hope that helps
I use XMLHttpRequest to read the PDF document
http://www.virtualmechanics.com/support/tutorials-spinner/Simple2.pdf
%PDF-1.3
%âãÏÓ
[...]
and print its content out to console:
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseText);
console.log('âãÏÓ');
}
};
xhr.open('GET', 'http://www.virtualmechanics.com/support/tutorials-spinner/Simple2.pdf', true);
xhr.send();
However, the console says
%PDF-1.3
%����
[...]
âãÏÓ
(The last line is from the reference console.log above to verify that the console can actually display those characters.)
Apparently, the characters are wrongly encoded at some point. What's going wrong and how to fix this?
XMLHttpRequest's default response type is text, but here one is actually dealing with binary data. Eric Bidelman describes how to work with it.
The solution to the problem is to read the data as a Blob, then to extract the data from the blob and plug it into hash.update(..., 'binary'):
var xhr = new XMLHttpRequest();
xhr.open('GET', details.url, true);
xhr.responseType = 'blob';
xhr.onload = function() {
if (this.status === 200) {
var a = new FileReader();
a.readAsBinaryString(this.response);
a.onloadend = function() {
var hash = crypto.createHash('sha1');
hash.update(a.result, 'binary');
console.log(hash.digest('hex'));
};
}
};
xhr.send(null);
The MIME type of your file might not be UTF-8. Try overriding it as suggested here and depicted below:
xhr.open('GET', 'http://www.virtualmechanics.com/support/tutorials-spinner/Simple2.pdf', true);
xhr.overrideMimeType('text/xml; charset=iso-8859-1');
xhr.send();
I have a text file on my server and I want to upload a text in it using XMLHttpRequest. It is downloaded successfully via GET method, but when I try to POST it I get 404 error.
var r1 = new XMLHttpRequest();
r1.open("GET", "db.txt", false);
r1.send();
var str = r1.responseText + "foo text";
var r2 = new XMLHttpRequest();
r2.open("POST", "db.txt", false);
r2.send(str);
Doing a direct upload as you're trying would be a security concern in most places and is generally not permitted... What you need to do is have a middle layer on your server to handle the request and write the file to disk safely.
You can easily upload a file using something like this:
var jsonBlob = new Blob([someJSON], {type: "text/plain;charset=utf-8"});
var data = new FormData();
data.append("filename", "new.json");
data.append("json", jsonBlob);
var xhr = new XMLHttpRequest();
var postURL = "http://example.com/post_target";
xhr.open("POST", postURL, true);
xhr.onload = function(e) {
if (this.status == 200) {
console.log(e.target.response);
}
};
xhr.send(data);
Where postURL is an endpoint which can handle file uploads.
If you post what language(s) you have available on your server (PHP?) I can give some example code to handle the upload on the server's end.