Javascript XHR file upload progress not working with OPTIONS - javascript

I have a file upload form to Amazon S3 direct from the browser, the upload works fine but I am unable to track the progress of the upload - it instantly shows 100%.
The reason I think is because it is posting to an external domain, Amazon, and it reports 100% on the return of the initial OPTIONS request which is sent. Is there any way I can ignore this response and track the 'progress' event that follows?
var xhr = new XMLHttpRequest();
xhr.open("POST", s3Data.url);
var postData = new FormData();
for(key in s3Data.fields){
postData.append(key, s3Data.fields[key]);
}
postData.append('file', file);
xhr.onreadystatechange = function() {
if(xhr.readyState === 4){
if(xhr.status === 200 || xhr.status === 204){
// complete
}
else{
alert("Could not upload file.");
}
}
};
xhr.upload.addEventListener("progress", function(evt){
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
alert("Upload " + Math.round(percentComplete*100) + "% complete.");
}
}, false);
xhr.send(postData);
The progress event just fires once and alerts 100%, which seems to be on response from the S3 URL, the next request in the browser is the POST which is the file upload
Any help would be greatly appreciated, I couldn't find any similar questions but apologies if I missed the obvious

Related

Stream webcam/audio and save it as a file on server - Apache

I am curious about implementing one feature into my small project.
Basically, what I want is when I go to one specific page, I want to start recording video and audio with my webcam, and save that session in my Apache server. Now, the thing is that I want to stream that as a data, and not record it and then send that file to a server. The reason for that is because when I am done with that page, I will be transferred to a different page and I will not have time to do upload the whole video.
I have found this on one git page,
<?php
foreach(array('video', 'audio') as $type) {
if (isset($_FILES["${type}-blob"])) {
echo 'uploads/';
$fileName = $_POST["${type}-filename"];
$uploadDirectory = 'uploads/'.$fileName;
if (!move_uploaded_file($_FILES["${type}-blob"]["tmp_name"], $uploadDirectory)) {
echo(" problem moving uploaded file");
}
echo($fileName);
}
}
?>
And Javascript
var fileType = 'video'; // or "audio"
var fileName = 'ABCDEF.webm'; // or "wav"
var formData = new FormData();
formData.append(fileType + '-filename', fileName);
formData.append(fileType + '-blob', blob);
xhr('save.php', formData, function (fName) {
window.open(location.href + fName);
});
function xhr(url, data, callback) {
var request = new XMLHttpRequest();
request.onreadystatechange = function () {
if (request.readyState == 4 && request.status == 200) {
callback(location.href + request.responseText);
}
};
request.open('POST', url);
request.send(data);
}
but I am not sure if that is the streaming solution (as I mentioned), and not record and then upload.
I am using PHP with some Javascript and have Apache as a server.

Ajax taking too long to come back

I am recording 2-4 seconds of audio on my website and using Ajax I am posting it to the server. Some time this Ajax take 4-5 seconds, on the other hand some time it takes up to 2 minutes for uploading the same file. The file size is around 360kB. I want the Ajax to drop the file on the server and come back instantly and let the server keep processing it and meanwhile the user can start recording the next file.
I am using webRTC to record audios and working on Yii 1.x
//create FormData
var formData = new FormData();
formData.append(fileType + '-filename', fileName);
formData.append(fileType + '-blob', blob);
callback('Uploading ' + formData + ' recording to server.');
//ajax call
makeXMLHttpRequest('captureFile', formData, function(progress) {
if (progress !== 'upload-ended') {
callback(progress);
return ;
}
var initialURL = '<path to upload a file>';
callback('ended', initialURL + fileName);
});
function makeXMLHttpRequest(url, data, callback) {
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
callback('upload-ended');
}
};
request.open('POST', url);
request.send(data);
};
on success next ajax perform its operation for initiating recording of the next file.
How can I make sure that this ajax only drop the file to the server and return back and server process the file and not stall ajax to finish file processing.

Edit and Send back Image File User Uploads

I'm building a front-end interface for a back-end image edited process (don't know all the correct jargon).
Basically:
user should be able to upload an image file through the UI
which sends it to the server
where the image is edited in some way
then the UI should display the edited image
I'm using an XHR request with the POST method as shown below to send the image file to the server.
var fileSelect = document.getElementById('file-select');
var uploadButton = document.getElementById('upload-button');
uploadButton.onclick = function() {
this.innerHTML = 'Uploading...';
//---------------
var files = fileSelect.files
var formData = new FormData();
var file = files[0]
if (file.type.match('image.*')) {
formData.append('photos[]', file, file.name);
}
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://httpbin.org/post', true);
xhr.onload = function() {
if (xhr.status === 200) {
uploadButton.innerHTML = 'Upload';
}
else {
alert('An error occurred!');
}
};
xhr.send(formData);
}; //end on-click 'Upload'
<input type="file" id="file-select" name="photos[]"/>
<button type="submit" id="upload-button">Upload</button>
My question is: In general, once the image file is sent to the server, by the code above, when/how does the edited image get sent back?
Will it be sent back as part of the server response to my POST request, and thus accessible in my processRequest callback function (assuming the server is configured to process it that way)?
Do I have to send a GET request to get the edited file?
I do not have access to the server/back-end at this point in time, and just know how the UI is supposed to work.

Image src not updating after setRequestHeader call

I have two AJAX functions: one for an image file upload, one for a form info upload.
File Upload
function uploadFile(insertNodeID, inputFileID){
var img = document.getElementById(inputFileID).files[0];
var form_data = new FormData();
form_data.append('file[]', img, img.name);
var objXML = new XMLHttpRequest();
objXML.onprogress = updateProgress;
objXML.onload = function() {
if(objXML.readyState==4 && objXML.status==200) {
if(objXML.responseText !== 'no'){
document.getElementById(insertNodeID).src = objXML.responseText;
}
else{
errorInOut('There was a problem uploading the file.');
}
}
};
objXML.open('POST', baseURL+'ajax/admin_fileupload/', true);
objXML.send(form_data);
Form Info Upload
function uploadFormInfo(strURL, strData, type) {
strURL = baseURL+'ajax/'+strURL+'/';
var objXML = new XMLHttpRequest();
objXML.onreadystatechange = function() {
if (objXML.readyState == 4 && objXML.status == 200) {
returnXML(objXML.responseText, type);
}
};
objXML.open("POST", strURL, true);
objXML.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
objXML.send(strData);
They both work perfect independently.
The issue I'm running into is when I call the uploadFormInfo(), then call uploadFile(), the document.getElementById(insertNodeID).src does not render the uploaded image. It still uploads the image to the server and the responseText is the correct path to the image. I did a console.log on the .src of the id AFTER the I plugged in the new image and the .src is correct BUT, it never changes in the elements tab in Chome inspect. It also works fine BEFORE I call uploadFormInfo().
I've tried and number of things (sending a separate request header for the uploadFile) and nothing works.
I'm stumped.

make a post request in js and open its results in a new window

I have a js file, containing a folder myFunc(phone_number)
Now when this js function is called, I want to make a POST request to the URI https://pay.something.in:443/FetchPhone/ passing the json {'phone_number' : 10 digit phone no. } as input to the request
and show its output in a new window.
Can somebody tell me how do I do that?
Seems to me like you want to make a POST request with xhr.
var xhr = new XMLHttpRequest();
xhr.open('POST', "https://pay.something.in:443")
xhr.setRequestHeader("Content-type", "application/json");
xhr.send( '{"phone_number" : 4455566677 }' );
xhr.onreadystatechange = function(){
if (xhr.readyState != 4) return;
if (xhr.status != 200 && xhr.status != 304) {
alert('HTTP error ' + req.status);
return;
}
console.log(xhr.responseText);//this is your response
window.sessionStorage['response'] = xhr.responseText;
window.open('Your window');//The data is accessible through sessionStorage.
}

Categories

Resources