hi i am using this JavaScript and it sends data correctly but the problem is temp file contains only this when i try to upload at server end
blob:https://sitename.com/03f06abe-6d00-4c4d-86bd-317db4bff616.wav
when i use php move_uploaded_file it writes the data to the given path but instead of real audio file it just writes the link of blob
i want to upload the wav or mp3 file of recorded audio. i have got code from this link and seems everything is working except data is not audio its just blob link when we move_uploaded_file use
Record and upload audio in jquery and php
here is my jquery
jQuery(document).ready(function () {
var $ = jQuery;
var myRecorder = {
objects: {
context: null,
stream: null,
recorder: null
},
init: function () {
if (null === myRecorder.objects.context) {
myRecorder.objects.context = new (
window.AudioContext || window.webkitAudioContext
);
}
},
start: function () {
var options = {audio: true, video: false};
navigator.mediaDevices.getUserMedia(options).then(function (stream) {
myRecorder.objects.stream = stream;
myRecorder.objects.recorder = new Recorder(
myRecorder.objects.context.createMediaStreamSource(stream),
{numChannels: 1}
);
myRecorder.objects.recorder.record();
}).catch(function (err) {});
},
stop: function (listObject) {
if (null !== myRecorder.objects.stream) {
myRecorder.objects.stream.getAudioTracks()[0].stop();
}
if (null !== myRecorder.objects.recorder) {
myRecorder.objects.recorder.stop();
// Validate object
if (null !== listObject
&& 'object' === typeof listObject
&& listObject.length > 0) {
// Export the WAV file
myRecorder.objects.recorder.exportWAV(function (blob) {
var url = (window.URL || window.webkitURL)
.createObjectURL(blob);
// Prepare the playback
var audioObject = $('<audio controls></audio>')
.attr('src', url);
var link = url+'.wav';
$('#audio').attr('value',link);
var blob = new Blob([link], {type: 'audio/wav'});
var reader = new FileReader();
reader.onload = function () {
var b64 = reader.result.replace(/^data:.+;base64,/, '');
};
reader.readAsDataURL(blob);
var form_data = new FormData();
form_data.append('file', blob);
$.ajax({
url: "upload_recording1.php",
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(data) {
}
});
});
}
}
}
};
});
my php is this
if(isset($_FILES['file']) and !$_FILES['file']['error']){
move_uploaded_file($_FILES['file']['tmp_name'], "saved_audio/11.wav");
}
=================================
edit 1 , ajax inside reader.onload same issue
jQuery(document).ready(function () {
var $ = jQuery;
var myRecorder = {
objects: {
context: null,
stream: null,
recorder: null
},
init: function () {
if (null === myRecorder.objects.context) {
myRecorder.objects.context = new (
window.AudioContext || window.webkitAudioContext
);
}
},
start: function () {
var options = {audio: true, video: false};
navigator.mediaDevices.getUserMedia(options).then(function (stream) {
myRecorder.objects.stream = stream;
myRecorder.objects.recorder = new Recorder(
myRecorder.objects.context.createMediaStreamSource(stream),
{numChannels: 1}
);
myRecorder.objects.recorder.record();
}).catch(function (err) {});
},
stop: function (listObject) {
if (null !== myRecorder.objects.stream) {
myRecorder.objects.stream.getAudioTracks()[0].stop();
}
if (null !== myRecorder.objects.recorder) {
myRecorder.objects.recorder.stop();
// Validate object
if (null !== listObject
&& 'object' === typeof listObject
&& listObject.length > 0) {
// Export the WAV file
myRecorder.objects.recorder.exportWAV(function (blob) {
var url = (window.URL || window.webkitURL)
.createObjectURL(blob);
// Prepare the playback
var audioObject = $('<audio controls></audio>')
.attr('src', url);
var link = url+'.wav';
$('#audio').attr('value',link);
var blob = new Blob([link], {type: 'audio/wav'});
var reader = new FileReader();
reader.onload = function () {
var b64 = reader.result.replace(/^data:.+;base64,/, '');
var form_data = new FormData();
form_data.append('file', blob);
$.ajax({
url: "upload_recording1.php",
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(data) {
}
});
};
reader.readAsDataURL(blob);
});
}
}
}
};
});
Related
Hello im new'ish in using and editing api's and im a bit stumped on TUI's Image Editor.
I'm trying to get the image data as a variable so that I can upload it separately to a website instead of just downloading it to the computer.
I am using this person's version of tui. I tried other methods as well but they didn't quite worked out for me.
const imageEditor = new tui.ImageEditor('#tui-image-editor-container', {
includeUI: {
loadImage: {
path: 'img/sampleImage2.png',
name: 'SampleImage',
},
theme: blackTheme, // or whiteTheme
initMenu: 'filter',
menuBarPosition: 'bottom',
},
cssMaxWidth: 700,
cssMaxHeight: 500,
usageStatistics: false,
});
window.onresize = function () {
imageEditor.ui.resizeEditor();
}
document.querySelector('#downloadButton').addEventListener('click', () => {
const myImage = instance.toDataURL();
document.getElementById("url").innerHTML = myImage;
});
</script>
<p id="url">Test</p>
Tried to change the code by using other guides but now it shows this error
Changed code
var imageEditor = new tui.ImageEditor('#tui-image-editor-container', {
includeUI: {
loadImage: {
path: 'img/sampleImage2.png',
name: 'SampleImage',
},
theme: blackTheme,
initMenu: 'filter',
menuBarPosition: 'left'
},
cssMaxWidth: 700,
cssMaxHeight: 1000,
usageStatistics: false
});
window.onresize = function() {
imageEditor.ui.resizeEditor();
}
function dataURLtoBlob(dataurl) {
var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
while(n--){
u8arr[n] = bstr.charCodeAt(n);
}
return new Blob([u8arr], {type:mime});
}
jQuery(document).ready(function ($) {
$('.tui-image-editor-download-btn').on('click', function (e) {
var blob = dataURLtoBlob(imageEditor.toDataURL());
var formData = new FormData();
formData.append('croppedImage', blob, 'sampleimage.png');
$.ajax({
url: '/files/upload_files/', // upload url
method: "POST",
data: formData,
success: function (data) {
alert('UPLOADED SUCCESSFULLY, PLEASE TRY AGAIN...');
},
error: function(xhr, status, error) {
alert('UPLOAD FAILED, PLEASE TRY AGAIN...');
}
});
return false;
});
});
</script>
Added in some false statements so that the object form can be sent.
jQuery(document).ready(function ($) {
$('.tui-image-editor-download-btn').on('click', function (e) {
var blob = dataURLtoBlob(imageEditor.toDataURL());
var formData = new FormData();
formData.append('croppedImage', blob, 'sampleimage.png');
$.ajax({
contentType: false, //added
processData: false, //added
url: '/files/upload_files/', // upload url
method: "POST",
data: formData,
success: function (data) {
alert('UPLOADED SUCCESSFULLY, PLEASE TRY AGAIN...');
},
error: function(xhr, status, error) {
alert('UPLOAD FAILED, PLEASE TRY AGAIN...');
}
});
return false;
});
});
Due to the timeout issues, I have converted the download to ajax short calls, and part downloads. Now I need those part CSV files to merge into one using js or jquery.
The code is given below.
$(document).on('click', '#downloadCaratReportAjax', function () {
var statusId = 1;
$.ajax({
url: '/admin-reports/carat/download-report',
type: 'POST',
beforeSend: function () {
$('#spiner-load-please-wait').modal({
backdrop: 'static',
keyboard: false
});
},
cache: false,
async: false,
data: {
statusId: statusId
},
success: function (res) {
var csvFile = new Blob([res]);
var downloadLink = document.createElement("a");
var blob = new Blob(["\ufeff", csvFile]);
var url = URL.createObjectURL(blob);
downloadLink.href = url;
downloadLink.download = "draft-campaigns-cost.csv";
document.body.appendChild(downloadLink);
downloadLink.click();
document.body.removeChild(downloadLink);
},
error: function (res) {
},
}).promise().done(function () {
var statusId = 2;
$.ajax({
url: '/admin-reports/carat/download-report',
type: 'POST',
beforeSend: function () {
$('#spiner-load-please-wait').modal({
backdrop: 'static',
keyboard: false
});
},
cache: false,
async: false,
data: {
statusId: statusId
},
success: function (res) {
var csvFile = new Blob([res]);
var downloadLink = document.createElement("a");
var blob = new Blob(["\ufeff", csvFile]);
var url = URL.createObjectURL(blob);
downloadLink.href = url;
downloadLink.download = "approved-campaign-cost.csv";
document.body.appendChild(downloadLink);
downloadLink.click();
document.body.removeChild(downloadLink);
},
error: function (res) {
},
})
}).promise().done(function () {
and upto four promises for individual csvs. Now i need all these csv files into one. I have searched all over the internet and found nothing. Please help.
getMediaBinary: function() {
var file = document.getElementById('photo').files[0],
reader = new FileReader(),
deferred = $.Deferred();
reader.onloadend = function () {
return deferred.resolve(reader.result);
};
reader.readAsBinaryString(file);
return deferred.promise();
},
getMediaData: function() {
var file = document.getElementById('photo').files[0],
reader = new FileReader(),
deferred = $.Deferred();
reader.onloadend = function () {
return deferred.resolve(reader.result);
};
reader.readAsDataURL(file);
return deferred.promise();
},
uploadMedia: function() {
var formData = new FormData();
$.when(JTWEET.getMediaBinary(), JTWEET.getMediaData() ).then(function(media, media_data) {
formData.append('media', media);
formData.append('media_data', media_data);
return $.ajax({
url: JTWEET.routerUrl + 'https://upload.twitter.com/1.1/media/upload.json',
type: 'POST',
// data: { media: document.getElementById('photo').files[0].name, media_data: JTWEET.getMediaData() },
data: formData,
contentType: false,
processData: false,
success: function() {
console.dir(arguments);
},
error: function() {
console.dir(arguments);
}
});
});
},
I'm getting the next error:
{"errors":[{"code":38,"message":"media parameter is missing."}]}
What am I missing ?
Try checking this one out - https://twittercommunity.com/t/post-media-upload-json-always-returns-media-parameter-is-missing/27962
Figured it out finally. Two things are important here:
1. the parameter name has to be “media”, not “media[]”
2. Do not set the contentType property. It prevents a Content-Type header with the correct boundary value from being automatically created.
A correct options object looks like this:
var options = {
"oAuthServiceName":"twitter",
"oAuthUseToken":"always",
method: "POST",
payload: { "media" : imageblob }
};
I want to find a way,give a dom as parameter and get data, from image_preview.
and separate image_preview.model() and image_preivew.on_chage() is event handler
make image_preview reusable not hardcode inside
I espect I will call image_preview pass dom in parameter, and return src as response , then I can use repsponse do something like append ...
var image_preview = {
on_change: function(wrap_dom, input_dom) {
$(wrap_dom).on('change', input_dom, function(event) { // I have to use on change because there are possible the `input dom` is new append...
var el_obj = $(this)[0];
var form_data = new FormData();
var file_length = el_obj.files.length;
for (var i = 0; i < file_length; i++) {
form_data.append("file[]", el_obj.files[i]);
}
image_preview.model(form_data).done(function(response) {
// console.log(response); // this is work
return response;
});
});
},
model: function(form_data) {
return $.ajax({
url: uri_public+'/admin/ajax/preview_file',
type: 'POST',
data: form_data,
processData: false,
contentType: false,
// async: false
});
}
}
var app_thumbnail = {
preview_controller: function() {
var wrap_dom = '.thumbnail';
var input_dom = '.upload-form input';
var result = image_preview.on_change(wrap_dom, input_dom);
// pass result to render view like append dom....
},
render: function() {
},
}
app_thumbnail.preview_controller();
Here is the easiest thing you can do:
var image_preview = {
on_change: function(wrap_dom, input_dom) {
$(wrap_dom).on('change', input_dom, function(event) {
var el_obj = $(this)[0];
var form_data = new FormData();
var file_length = el_obj.files.length;
for (var i = 0; i < file_length; i++) {
form_data.append("file[]", el_obj.files[i]);
}
image_preview.model(form_data).done(function(response) {
app_thumbnail.preview_controller(response);
});
});
},
model: function(form_data) {
return $.ajax({
url: uri_public+'/admin/ajax/preview_file',
type: 'POST',
data: form_data,
processData: false,
contentType: false,
// async: false
});
}
}
var app_thumbnail = {
preview_controller: function(response) {
var wrap_dom = '.thumbnail';
var input_dom = '.upload-form input';
var result = response;
}
}
// If you want to initialize it.
// image_preview.on_change(..., ...);
My english is not good, but I will try to explain the problem. I'm trying to load multiple images in an asp.net webforms application, but when I'm loading the files the first image doesn't load. Look at the following code:
$('#loadImg').change(function () {
for (var i = 0; i <= this.files.length; i++) {
if (this && this.files[i]) {
var reader = new FileReader(), valor;
reader.readAsDataURL(this.files[i]);
reader.onload = function () {
valor = reader.result
};
var obj = new Object();
obj.Objn = i;
obj.Name = this.files[i].name;
obj.Tipo = this.files[i].type;
obj.Peso = this.files[i].size;
obj.Obji = valor;
var params = JSON.stringify(obj);
if (IsValid(obj.Tipo)) {
$.ajax({
type: "POST",
url: uri1,
data: params,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
if (data.d) {
$('#objimg').attr('src', obj.Obji);
}
},
async: false,
error: function (XMLHttpRequest) {
alert("Error al cargar la imagen");
}
});
}
}
}
function IsValid(iTipo) {
switch (iTipo) {
case 'image/png': case 'image/gif': case 'image/jpeg': case 'image/pjpeg':
return true; break;
default:
return false;
}
}