I want to upload a file using XMLHTTRequest for Safari 5.1 and pass parameters in the POST request.How can this be achieved?It should be in plain javascript without using any API and I am doing this as Safari does not support FileReader in 5.1 version.
var fd = new FormData();
fd.append('file', $files[i]);
var xhr = new XMLHttpRequest();
xhr.addEventListener("load", function(){alert("Done!");}, false);
xhr.open("POST", url.getUrl('myurl'));
xhr.send(fd);
Is the above piece of code correct?How do I pass parameters to the POST request.
The code looks good.
If you want to pass additional parameters to the POST you will have to add them to the FormData.
var fd = new FormData();
// here the POST parameters
fd.append('parameter1', 'XXXX' );
fd.append('parameter2', 'YYYY' );
// The rest of your code
fd.append('file', $files[i]);
...
EDIT: I am not sure however if this functionality is supported in Safari 5.1
Try if( window.FormData === undefined ) or if( window.FormData !== undefined ).
for more reference click here
You should also try this one!
<script>
var client = new XMLHttpRequest();
function upload()
{
var file = document.getElementById("uploadfile");
/* Create a FormData instance */
var fd = new FormData();
/* Add the file */
fd.append("upload", file.files[0]);
client.open("post",url.getUrl('myurl'), true);
client.setRequestHeader("Content-Type", "multipart/form-data");
client.send(formData); /* Send to server */
}
/* Check the response status */
client.onreadystatechange = function()
{
if (client.readyState == 4 && client.status == 200)
{
alert(client.statusText);
}
}
</script>
As FormData, the ability to send() one, and the upload property (and its onprogress event) are all part of XMLHttpRequest level 2, you can test for .upload to see if you've got a level 2. I don't have a Mac handy, but the function (sadly, but correctly) returns false for Opera 11.50 (and true for Firefox 4).
Related
I've read the readme file at https://github.com/cloudinary/cloudinary_tinymce but still can't understand how to do it. Plus they do it on Ruby on Rails, which doesn't really help.
Do I really need to do server-side endpoint? It only asks for a signed URL. But I don't need it to be signed. How do I do it within JavaScript and HTML alone? I don't want to do anything inside my server except to render templates.
edit: I tried it with image_upload handler and it uploads to my Cloudinary account. But it won't give me the url for the image on successful upload (I expect to get something like https://res.cloudinary.com/strova/image/upload/v1527068409/asl_gjpmhn.jpg). Here's my code:
images_upload_handler: function (blobInfo, success, failure) {
var xhr, formData;
xhr = new XMLHttpRequest();
xhr.withCredentials = false;
xhr.open('POST', 'https://api.cloudinary.com/v1_1/strova/upload');
xhr.onload = function () {
var json;
if (xhr.status !== 200) {
failure('HTTP Error: ' + xhr.status);
return;
}
json = JSON.parse(xhr.responseText);
success(json.location);
};
formData = new FormData();
formData.append('file', blobInfo.blob(), blobInfo.filename());
formData.append('upload_preset', cloudinary_upload_preset);
xhr.send(formData);
}
Try "faking" a POST request for one. I am still trying. To figure out why the documentation "requires" a POST request. The PHP example: https://www.tinymce.com/docs-3x//TinyMCE3x#Installation/ just echos back what gets POSTED to server. The plugin must be interpolated the posted content.
Inspired by your code, I was able to resolve this pain point for myself. The missing part was that after parsing the response, the secure_url from the response needed to be called and assigned to json in the format required by TinyMCE. Following is the code:
images_upload_handler: function (blobInfo, success, failure) {
var xhr, formData;
xhr = new XMLHttpRequest();
xhr.withCredentials = false;
//restricted it to image only using resource_type = image in url, you can set it to auto for all types
xhr.open('POST', 'https://api.cloudinary.com/v1_1/<yourcloudname>/image/upload');
xhr.onload = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var response = JSON.parse(xhr.responseText);
var url = response.secure_url; //get the url
var json = {location: url}; //set it in the format tinyMCE wants it
success(json.location);
}
};
formData = new FormData();
formData.append('file', blobInfo.blob(), blobInfo.filename());
formData.append('upload_preset', '<YourUnsignedUploadPreset>');
xhr.send(formData);
}
Server-side dev here who's a JS newbie (1 week old). This question is about browser compatibility issues (mobile browsers especially).
I'm trying to use pure JS/Ajax to process image uploads via a web form. Specifically, at one point I'm using the append method on FormData() with filename.
Here's the code:
function overwrite_default_submit(e) {
// block the default behavior
e.preventDefault();
// create and populate the form with data
var form_data = new FormData();
form_data.append("image", img_to_send, img_name);
// send the form via AJAX
var xhr = new XMLHttpRequest();
xhr.open('POST', e.target.action);
xhr.send(form_data);
}
According to https://developer.mozilla.org/en-US/docs/Web/API/FormData/append, browser compatibility for append in mobiles is not universal. Two problems cited are:
XHR in Android 4.0 sends empty content for FormData with blob.
And
Prior to Gecko 7.0 (Firefox 7.0 / Thunderbird 7.0 / SeaMonkey 2.4),
if you specified a Blob as the data to append to the object, the
filename reported in the "Content-Disposition" HTTP header was an
empty string; this resulted in errors being reported by some servers.
Starting in Gecko 7.0 the filename "blob" is sent.
My questions are:
1) What alternative can I use to fix these specific situations?
2) What checks can I put in place to elegantly fall back (e.g. to a non-JS solution - which I've already implemented) in case there's just no way through?
Would love to see illustrative examples of how the experts do it.
In case warranted, here's my full code:
// converting image data uri to a blob object
function dataURItoBlob(dataURI,mime_type) {
var byteString = atob(dataURI.split(',')[1]);//supported
var ab = new ArrayBuffer(byteString.length);//supported
var ia = new Uint8Array(ab);//supported
for (var i = 0; i < byteString.length; i++) { ia[i] = byteString.charCodeAt(i); }//supported
return new Blob([ab], { type: mime_type });
}
The above is called in the following:
var canvas = document.createElement('canvas');
canvas.width = img_width;
canvas.height = img_height;
var ctx = canvas.getContext("2d");
ctx.drawImage(source_img, 0, 0, img_width, img_height);
return dataURItoBlob(canvas.toDataURL(mime_type,quality/100),mime_type);
And ultimately, the returned blob is appended to a FormData() object and sent via Ajax:
function overwrite_default_submit(e) {
// block the default behavior
e.preventDefault();
// create and populate the form with data
var form_data = new FormData();
form_data.append("image", img_blob, img_name);
// send the form via AJAX
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
xhr.open('POST', e.target.action);
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr.send(form_data);
}
var formdata = new FormData();
var xhr = null;
if(typeof XMLHttpRequest != "undefined"){
xhr = new XMLHttpRequest();
}
else if(typeof window.ActiveXObject != "undefined"){
try {
xhr = new ActiveXObject("Msxml2.XMLHTTP.4.0");
}
catch(e){
try {
xhr = new ActiveXObject("MSXML2.XMLHTTP");
}
catch(e){
try {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e){
xhr = null;
}
}
}
}
xhr.open("GET",url, true); ///fileUploadTester/FileUploader
xhr.send(formdata);
xhr.responseType = "arraybuffer";
xhr.onload = function(e) {
var ua = window.navigator.userAgent;
var msie = ua.indexOf("MSIE ");
if (msie > 0) // If Internet Explorer, return version number
{
var urlIE = URL;
window.location = urlIE;
}
else
{
window.location = this.responseURL;
}
};
}
The above code is from my javaScript method when i call that method my requirement is to download file for user.
In java i have a method to generate file and add it to response
For other browsers i am able to call the method and get response back but for IE 11 i am not able to do.
Any Solution for this or any errors in my code?
Got the Answer The way i was getting browser name was wrong.
Once i got correct browser name using javascript it stated working
FormData() is not supported by ie11.u can build the formdata string by yourself.
function sendData(data) {
console.log('Sending data');
const XHR = new XMLHttpRequest();
const urlEncodedDataPairs = [];
// Turn the data object into an array of URL-encoded key/value pairs.
for (const [name, value] of Object.entries(data)) {
urlEncodedDataPairs.push(`${encodeURIComponent(name)}=${encodeURIComponent(value)}`);
}
// Combine the pairs into a single string and replace all %-encoded spaces to
// the '+' character; matches the behavior of browser form submissions.
const urlEncodedData = urlEncodedDataPairs.join('&').replace(/%20/g, '+');
// Define what happens on successful data submission
XHR.addEventListener('load', (event) => {
alert('Yeah! Data sent and response loaded.');
});
// Define what happens in case of an error
XHR.addEventListener('error', (event) => {
alert('Oops! Something went wrong.');
});
// Set up our request
XHR.open('POST', 'https://example.com/cors.php');
// Add the required HTTP header for form data POST requests
XHR.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
// Finally, send our data.
XHR.send(urlEncodedData);
}
check this for more
I'm currently looking at
function readDataFromURL(fuFullHttpURL, fuCallMeOnLoad) {
var MyThis = this;
this.fullHttpURL = fuFullHttpURL;
this.callMeOnLoad = fuCallMeOnLoad;
var oReq = new XMLHttpRequest();
oReq.open("GET", MyThis.fullHttpURL, true);
oReq.responseType = "arraybuffer";
oReq.onload = function(oEvent) {
var blob = new Blob([oReq.response], {type: "image/jpg"});
MyThis.callMeOnLoad(blob);
};
oReq.send();
}
But that is only for download. How do I upload with this code?
And when I tried downloading an image with xmlhttprequest in former years there was a size restriction to the download. Is there still a size restriction?
In former times every browser handeled this size-restriction differently, so I can't test this myself.
Edit: https://stackoverflow.com/a/18120473/3716796 seems to explain uploading.
You can use FormData to send files in XMLHttpRequest like below . Although Chrome & FF support it well, it works only in IE10 or above.
var xhr = new XMLHttpRequest();
var file = document.getElementById("fileUpload");
var formData = new FormData();
formData.append("upload", file.files[0]);
xhr.open("post", "your-url", true);
xhr.setRequestHeader("Content-Type", "multipart/form-data");
xhr.upload.onload = function(event){
// handle successful upload
};
xhr.send(formData);
Let's say I have a text file on my web server under /today/changelog-en.txt which stores information about updates to my website. Each section starts with a version number, then a list of the changes.
Because of this, the first line of the file always contains the latest version number, which I'd like to read out using plain JavaScript (no jQuery). Is this possible, and if yes, how?
This should be simple enough using XHR. Something like this would work fine for you:
var XHR = new XMLHttpRequest();
XHR.open("GET", "/today/changelog-en.txt", true);
XHR.send();
XHR.onload = function (){
console.log( XHR.responseText.slice(0, XHR.responseText.indexOf("\n")) );
};
So seeing as the txt file is externally available ie: corresponds to a URL, we can do an XHR/AJAX request to get the data. Note without jQuery, so we'll be writing slightly more verbose vanilla JavaScript.
var xmlHttp;
function GetData( url, callback ) {
xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = callback;
xmlHttp.open( "GET", url, true );
xmlHttp.send( null );
}
GetData( "/today/changelog-en.txt" , function() {
if ( xmlHttp.readyState == 4 && xmlHttp.status == 200 {
var result = xmlHttp.responseText;
var allLines = result.split("\n");
// do what you want with the result
// ie: split lines and show the first line
var lineOne = allLines[0];
} else {
// handle the error
}
});