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 }
};
Related
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);
});
}
}
}
};
});
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;
});
});
I have an ASP.NET MVC Application where I have a method, which returns a list of Objects:
public List<FileObject> GetAllFilesFromDirectory()
{
string filePath = #"C:\FilesToWatch";
string[] fileEntries = Directory.GetFiles(filePath, "*.txt", SearchOption.TopDirectoryOnly);
FileObject fo;
List<FileObject> list = new List<FileObject>();
foreach (var file in fileEntries)
{
FileInfo info = new FileInfo(file);
fo = new FileObject
{
FileName = info.Name, //asdf.txt
FilePath = info.FullName //C:\FilesToWatch\asdf.txt
};
list.Add(fo);
}
return list;
}
Now I want to return this list in javascript:
$.ajax({
type: "GET",
url: "Home/GetAllFilesFromDirectory",
data: ???,
success: function () {
console.log('success');
},
error: function () {
console.log('error');
},
complete: function (data) {
console.log('complete');
}
});
I know, that I have to add the data: attribute, but I do not really know, what I should write after data: to return this list.
You do not need to pass data as your controllerAction accepting no arguments. Here is more clear result you can return from your controllerAction as follow:
public ActionResult GetAllFilesFromDirectory()
{
string filePath = #"C:\FilesToWatch";
string[] fileEntries = Directory.GetFiles(filePath, "*.txt",
SearchOption.TopDirectoryOnly);
FileObject fo;
List<FileObject> list = new List<FileObject>();
foreach (var file in fileEntries)
{
FileInfo info = new FileInfo(file);
fo = new FileObject
{
FileName = info.Name, //asdf.txt
FilePath = info.FullName //C:\FilesToWatch\asdf.txt
};
list.Add(fo);
}
return Json(new { filesList = list }, JsonRequestBehaviour.AllowGet);
}
And then you can read the response in ajax as follow:
$.ajax({
type: "GET",
url: "Home/GetAllFilesFromDirectory",
success: function (resp) {
if(resp.filesList)
{
$.each(function( index, element ) {
console.log(element.FileName ); // i.e log the file name
});
}
},
error: function () {
console.log('error');
},
complete: function (data) {
console.log('complete');
}
});
enter code hereI have read several answers about this question, but no one works.
I have the following code but my HttpPostedFileBase[] array is always null.
The Other parameters has the right value, but the HttpPostedFileBase[] is always null.
What am i missing??
$('#myFile').on('change', function (e) {
var fileName = e.target.files[0].name;
archivosProcesar = new FormData();
for (var i = 0; i <= e.target.files.length -1; i++) {
archivosProcesar.append(i, e.target.files[i]);
}
});
function aplicarFragmentacion() {
var ids = obtenerAfiliadosSeleccionados();
var data = {
fragmento1: parseInt($('#fragmento1').val()),
fragmento2: parseInt($('#fragmento2').val()),
segmentos: ids,
archivos: archivosProcesar
}
if (!validarProcentajes() & !validarSeleccionados(ids)) {
$.ajax({
data: data,
url: urlAplicarFrag,
type: 'POST',
processData: false,
beforeSend: function () {
//$("#resultado").html("Procesando, espere por favor...");
},
success: function (data) {
onSuccessAplicarFragmentacion(data);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR.responseText);
onError(jqXHR.responseText);
}
});
}
}
Controller.cs
public async Task<ActionResult> AplicarFragmentacion(decimal fragmento1, decimal fragmento2, string[] segment\
os, HttpPostedFileBase[] archivos)
{
List<Credito> lstSegmentos = new List<Credito>();
try
{
ProgressHub.SendMessage("Iniciando proceso de fragmentación...", 10);
lstSegmentos = await FragmentacionNegocio.AplicarFragmentacion(fragmento1, fragmento2, segmentos)\
;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
return Json(lstSegmentos, JsonRequestBehavior.AllowGet);
}
Try submitting a FormData object, not an anonymous object with a FormData field. Also it is my understanding that the contentType should be set to false.
var formData = new FormData();
formData.append('fragmento1', parseInt($('#fragmento1').val());
formData.append('fragmento2', parseInt($('#fragmento2').val());
formData.append('segmentos', obtenerAfiliadosSeleccionados());
formData.append('archivos', $('#fileupload')[0].files[0]);
$.ajax({
type: 'POST',
data: formData,
url: urlAplicarFrag,
type: 'POST',
processData: false,
contentType: false,
[...]
});
The fix was to use this plug in
https://jquery-form.github.io/form/
In this way
$(this).ajaxSubmit({
url: urlAplicarFrag,
data: {
fragmento1: parseInt($('#fragmento1').val()),
fragmento2: parseInt($('#fragmento2').val()),
segmentos: ids,
fechaReenvio: $('#fecha-reenvio').val()
},
success: function (data) {
onSuccessAplicarFragmentacion(data);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR.responseText);
onError(jqXHR.responseText);
}
});
check the plugin website
I have the following:
var q = new app.models.OverwriteLineItemsProcess();
q.set('id', $("#process_id").val());
q.saveSource($("#source_quote").val());
q.lockSource();
saveSource is sending data to the backend using ajax. So is lockSource.
I want to execute in this SEQUENTIAL manner: saveSource >> lockSource.
How do I write the q.js to make it work?
By q.js, I mean https://github.com/kriskowal/q
UPDATE: added saveSource and lockSource
saveSource: function (quotation_id) {;
var type = "PUT";
var verb = "Updated";
var headers = {
'X-HTTP-Method-Override': type
};
var url = app.base_url + "/overwrite_line_items/" + this.id;
this.set('source_quote', quotation_id);
var data = this.toFormData();
var result = false;
var currentModel = this;
var settings = {
headers: headers,
type: type,
url: url,
data: data,
success: function(json) {
response = JSON && JSON.parse(json) || $.parseJSON(json);
console.log(response);
currentModel.lockSource();
$("#facebox-source-quote-status").html('<font color="green">SELECTED</font>');
},
error: function(response) {
$("#facebox-source-quote-status").html('<font color="red">UNABLE TO SELECT</font>');
},
dataType: 'json'
};
$.ajax(settings).done(function() {
});
},
lockSource: function () {
var type = "PUT";
var verb = "Updated";
var headers = {
'X-HTTP-Method-Override': type
};
var url = app.base_url + "/quotations/is_editable/" + this.attributes.source_quote;
var data = this.toFormData();
var result = false;
var currentModel = this;
var settings = {
headers: headers,
type: type,
url: url,
data: data,
success: function(response) {
console.log(response);
},
error: function(response) {
$("#facebox-source-quote-status").html('<font color="red">UNABLE TO SELECT</font>');
},
dataType: 'json'
};
$.ajax(settings).done(function() {
});
},
The jQuery.ajax function which you're using already returns a promise for its result. You just need to return that from your functions:
saveSource: function (quotation_id) {;
…
var settings = {
headers: headers,
type: type,
dataType: 'json', // jQuery will automatically parse it for you
url: url,
data: data
};
return $.ajax(settings).done(function() {
// ^^^^^^
$("#facebox-source-quote-status").html('<font color="green">SELECTED</font>');
// notice I did remove the currentModel.lockSource(); call from the callback
}, function() {
$("#facebox-source-quote-status").html('<font color="red">UNABLE TO SELECT</font>');
});
},
lockSource: function () {
…
var settings = // analoguous, no callbacks here
return $.ajax(settings).fail(function(response) {
$("#facebox-source-quote-status").html('<font color="red">UNABLE TO SELECT</font>');
});
}
Now you can easily chain them:
var q = new app.models.OverwriteLineItemsProcess();
q.set('id', $("#process_id").val());
q.saveSource($("#source_quote").val()).then(function(saveResponse) {
console.log(saveResponse);
return q.lockSource();
}).done(function(lockResponse) {
console.log(lockResponse);
});
You don't even need Q for that. If you want to use it, wrap the $.ajax() calls in a Q() invocation, as explained in the Converting JQuery Promises to Q section of the docs.