I'm recording video and audio from the browser using MediaRecorder. After I finish recording I try to upload it to the server with something like this:
function upload() {
var fileName = 'video.webm';
var formData = new FormData();
formData.append('filename', fileName);
formData.append('blob', blobs);
$.ajax({
type: 'POST',
url: '/upload.php',
data: formData,
processData: false,
contentType: false
}).done(function(data) {
console.log(data);
});
xhr('upload.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) {
alert('Done');
}
};
request.open('POST', url);
request.send(data);
}
}
Apparently the $_FILES variable doesn't get set in php, but the $_POST does. The file name has been passed correctly, but if I output the blobs to a file, I'm not able to reproduce the file in an html5 video object, so I guess something is wrong with that.
Could anyone explain what's the best way to accomplish this upload?
Thanks
Related
I am trying to download the file using this function but I am not able to execute the function after first ajax success. I read other resources but it was not helpful, I am trying to achieve this from 2 days and regularly searching nothing happend.
Please helpme to create this function after first success response it will call the function as DownloadFile();
I am returning these array in the first success response -
current no any error showing only the first success response show and downlaodfile() function not run.
filename: "PO_21-22_0166.pdf"
path: "./folder/myfilename.pdf"
responseCode: "200"
status: "success"
Please help me, how I make it correct so I can download the file with the help of my created own code.
Where I am doing mistake and how it will after fix.
$.ajax({
cache: false,
type: "POST",
url: "example.com",
cache: false,
success: function(response) {
if (response.responseCode == '200') {
var fileName = response.filename;
var myurl = response.path;
function DownloadFile(fileName) {
//var myurl = response.path;
$.ajax({
url: myurl,
cache: false,
xhr: function() {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 2) {
if (xhr.status == 200) {
xhr.responseType = "blob";
} else {
xhr.responseType = "text";
}
}
};
return xhr;
},
success: function(data) {
//Convert the Byte Data to BLOB object.
var blob = new Blob([data], {
type: "application/octetstream"
});
//Check the Browser type and download the File.
var isIE = false || !!document.documentMode;
if (isIE) {
window.navigator.msSaveBlob(blob, fileName);
} else {
var url = window.URL || window.webkitURL;
link = url.createObjectURL(blob);
var a = $("<a />");
a.attr("download", fileName);
a.attr("href", link);
$("body").append(a);
a[0].click();
$("body").remove(a);
}
},
});
}
} else {
alert(response.message);
return false;
}
},
});
This code will send request to post parameters to php file:
var param = //some parameters;
var url = file.php;
xhttp.open("POST", url, true);
xhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhttp.send(params);
I got the response but the php file produce some output like <td><tr>.....
How to get this result of php in some div of my html?
Thanks,
You use onreadystatechange to get the response:
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
$('#mydiv').html(xhttp.responseText);
}
};
XHR is pretty complicated without using a Framework. Just use jQuery it will make this 1000x easier.
$.ajax({
url: "myfile.php",
type: "POST",
data: {
/* Params */
},
success: function(response){
/* Use your response here */
}
});
http://api.jquery.com/jquery.ajax/
I want to implement the following:
Call an ASHX hanlder from UI using Jquery.
Upload a file to this ASHX handler.
And when upload is complete, I want to keep sending messages from the server to UI (SSE) to tell the user about the execution status of the code in ASHX handler.
I am stuck with the 3rd point that has been mentioned above.
Following is the UI code that I have written:
var file = $("input#importFileInputHidden")[0].files[0];
var formData = new FormData();
formData.append('file', file);
importAjaxCall = $.ajax({
xhr: function () {
var xhr = new window.XMLHttpRequest();
$('#progressBar').show();
//Method to show the progress of the file being uploaded
xhr.upload.addEventListener("progress", function (evt) {
if (evt.lengthComputable) {
var percentComplete = Math.round((evt.loaded / evt.total) * 100);
$('#percentageImportComplete').text('' + percentComplete + '%');
$('#importStatus').css('width', percentComplete + '%');
}
}, false);
return xhr;
},
type: 'post',
url: "Handler.ashx",
data: formData,
processData: false,
contentType: false,
success: function (data) {
//Some code to show success status to user
});
How to capture the messages I am sending from the server?
Have to tried to look into responseText property of http request?
success: function () {
console.log(xhr.responseText);
});
I got a php file that saves file to server to a folder called upload it receives file via an ajax request every thing works fine so far the next requirement is to send a string along with the file to specify an upload folder & sub folder like "Course/Math" how to achieve that?
JS
$( document ).ready(function() {
$('#Upload').click(function(){
var formData = new FormData($('form')[0]);
$.ajax({
url: 'uploadFile.php',
type: 'POST',
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){
myXhr.upload.addEventListener('progress',progressHandling, false);
}
return myXhr;
},
success: completeHandler,
data: formData,
cache: false,
contentType: false,
processData: false
});
});
var progressHandling = function(e){
if(e.lengthComputable){
var percent = Math.round((e.loaded / e.total) * 100);
$('#uploadprogress').css('width', percent+'%');
}
}
var completeHandler = function(data){
$('#message').text(data);
$('#uploadprogress').css('width', '0%');
$('#file').val('');
};
});
PHP
<?php
if ($_FILES["file"]["error"] > 0) {
} else {
move_uploaded_file($_FILES["file"]["tmp_name"],
"upload/" . $_FILES["file"]["name"]);
echo true;
}
?>
Sample Example of Sending form data in ajax call with .serialize()
var formData = $('#myform').serialize;
$.ajax({
url: 'uploadFile.php',
type: 'POST',
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){
myXhr.upload.addEventListener('progress',progressHandling, false);
}
return myXhr;
},
success: completeHandler,
data: formData,
cache: false,
contentType: false,
processData: false
});
If you want to add a string simply use like following:
var value = 'test';
var formData = $('#myform').serialize+"&newstring="+value;
Update
File upload is not possible through ajax.
You can upload file, without refreshing page by using IFrame or AjaxFileUpload Plugin.
Further Details here is Answer.
Also file some detail explanation here also:
jQuery Ajax File Upload
jQuery Upload Progress and AJAX file upload
You could use the HTML5 Upload element.
$("#FileUpload").change(function (e) {
var uploadFile = e.target.files;
if (uploadFile.length > 0) {
if (window.FormData !== undefined) {
var data = new FormData();
for (var x = 0; x < uploadFile.length; x++) {
data.append("file" + x, uploadFile[x]);
}
data.append("ELEMENTCLASSNAME", $("#ELEMENTID").val());
$.ajax({
type: "POST",
url: 'URL',
contentType: false,
processData: false,
data: data,
success: function (result) {
alert(result);
},
failure: function (result) {
alert(result);
},
error: function (xhr, status, p3, p4) {
var err = "Error " + " " + status + " " + p3 + " " + p4;
if (xhr.responseText && xhr.responseText[0] == "{")
err = JSON.parse(xhr.responseText).Message;
console.log(err);
}
});
} else {
alert("This browser doesn't support HTML5 file uploads!");
}
}});
On the server side use the Request Object get the value:
var versionName = Request["ELEMENTCLASSNAME"];
I have image upload function in my "form" which gets uploaded via ajax. So, until image is uploading, User continues to fill rest of form. and than click on submit button which is another ajax function to submit whole form.
Problem is I have below function for image upload :-
jQuery(window).load(function(){
jQuery(':button').click(function(){
var formData = new FormData(jQuery('form')[0]);
jQuery.ajax({
url: 'upload.php', //Server script to process data
type: 'POST',
xhr: function() { // Custom XMLHttpRequest
var myXhr = jQuery.ajaxSettings.xhr();
if(myXhr.upload){ // Check if upload property exists
myXhr.upload.addEventListener('progress',progressHandlingFunction, false); // For handling the progress of the upload
}
return myXhr;
},
//Ajax events
beforeSend: function(e) { $('#progress').css('display', 'block'); },
success: function(e) {
if (e != "no" && e != 'dir') {
$('#img').attr("src", e);
$('#imglinktosent').val(e);
} else if (e == 'dir') {
alert('Oops! We could not find \image\ directory or may be permission is not correct');
} else {
alert('File was not Uploaded, Kindly Upload Image with Size less than 512KB');
}
} ,
error: function(e) { alert('error' + e.message); } ,
data: formData,
//Options to tell jQuery not to process data or worry about content-type.
cache: false,
contentType: false,
processData: false
});
});
function progressHandlingFunction(e){
if(e.lengthComputable){
$('progress').attr({value:e.loaded,max:e.total});
}
}
});//]]>
It was hindering my complete form submission, therefore i changed it into Below function.
function uploadimage(){
jQuery(':button').click(function(){
var formData = jQuery('#myfile').val();
jQuery.ajax({
url: 'upload.php', //Server script to process data
type: 'POST',
xhr: function() { // Custom XMLHttpRequest
var myXhr = jQuery.ajaxSettings.xhr();
if(myXhr.upload){ // Check if upload property exists
myXhr.upload.addEventListener('progress',progressHandlingFunction, false); // For handling the progress of the upload
}
return myXhr;
},
//Ajax events
beforeSend: function(e) { $('#progress').css('display', 'block'); },
success: function(e) {
if (e != "no" && e != 'dir') {
$('#img').attr("src", e);
$('#imglinktosent').val(e);
} else if (e == 'dir') {
alert('Oops! We could not find \image\ directory or may be permission is not correct');
} else {
alert('File was not Uploaded, Kindly Upload Image with Size less than 512KB');
}
} ,
error: function(e) { alert('error' + e.message); } ,
data: formData,
//Options to tell jQuery not to process data or worry about content-type.
cache: false,
contentType: false,
processData: false
});
});
function progressHandlingFunction(e){
if(e.lengthComputable){
$('progress').attr({value:e.loaded,max:e.total});
}
}
}
So, that whenever user clicks on "upload image" button. Image will get uploaded by "uploadimage()" function set on "button" with event "onclick".
But PHP was giving error with "undefined index myfile" in upload.php
After searching for a while, i found, There was "request payload" and no formdata option in header.
After searching more in stackoverflow, i found i have to specify this too :
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
as if you would have noticed at line 30, I am sending direct formData
data: formData,
//Options to tell jQuery not to process data or worry about content-type.
**
But I am unsure where should i specify
**
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
in my uploadimage() function to work.
Ajax doesn't support binary file transfers by default. I think it is more easy to base-64 encode your image and just post the data string to the server. You can use a html5 canvas element to get a base-64 encoded string from your image canvas.toDataURL(); . Server side you'll need to decode this string with base64_decode($yourimagedatastring);