i am using javascript to upload an image using the unsigned mode. the resultant image is a blank image or i can say an image filled with black color. not sure what is wrong. the code looks like follow:
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "https://api.cloudinary.com/v1_1/mycloud/image/upload", false);
xhttp.setRequestHeader("Content-type", "application/json");
xhttp.onreadystatechange = function() { //Call a function when the state changes.
if (xhttp.readyState == 4 && xhttp.status == 200) {
alert(xhttp.responseText);
} else {
alert("Error dude: " + xhttp.statusText);
}
}
var parameters = {
"file": imgData,
"upload_preset": "mycode"
};
xhttp.send(JSON.stringify(parameters));
resultant image is:
http://res.cloudinary.com/viksphotography/image/upload/v1490752341/irgvt7b3qwoug1vz7own.jpg
Please note that imgData is base64 encoded
You need to use FormData for uploading the file:
const cloudName = 'your cloud name';
const unsignedUploadPreset = 'your unsigned upload preset';
// Upload base64 encoded file to Cloudinary
uploadFile('data:image/gif;base64,R0lGODlhSAFIAf....');
// *********** Upload file to Cloudinary ******************** //
function uploadFile(file) {
var url = `https://api.cloudinary.com/v1_1/${cloudName}/upload`;
var xhr = new XMLHttpRequest();
var fd = new FormData();
xhr.open('POST', url, true);
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.onreadystatechange = function(e) {
if (xhr.readyState == 4 && xhr.status == 200) {
// File uploaded successfully
var response = JSON.parse(xhr.responseText);
// https://res.cloudinary.com/cloudName/image/upload/v1483481128/public_id.jpg
var url = response.secure_url;
// Create a thumbnail of the uploaded image, with 150px width
var tokens = url.split('/');
tokens.splice(-2, 0, 'w_150,c_scale');
var img = new Image(); // HTML5 Constructor
img.src = tokens.join('/');
img.alt = response.public_id;
document.body.appendChild(img);
}
};
fd.append('upload_preset', unsignedUploadPreset);
fd.append('tags', 'browser_upload'); // Optional - add tag for image admin in Cloudinary
fd.append('file', file);
xhr.send(fd);
}
See full example here. It will upload a small Michael Jordan jumpman image to your account.
Related
I'm using TinyMCE 5 with PHP 7.
Currently:
1. images_upload_handler (working)
Following the TinyMCE guide on Drag-in uploading images, and my own PHP upload AJAX handler, I got an image to upload successfully to my uploads directory:
This correctly uploads the file and keeps the correct name, using AJAX.
It uses a function for images_upload_handler, calling my AJAX handler.
2. file_picker_callback (incomplete)
Following the TinyMCE demo on uploading files, I got these two toolbar buttons (image, media) to show an upload button in their dialogs:
This works for image, not media.
It uses a function for file_picker_callback, uploading its own way.
3. The problem
I can't get the file_picker_callback from 2. to upload from media and I want it to use my own AJAX upload handler anyway, which I can't.
Using the image tool to upload, it will save the file after clicking "Save" in the dialog. But, when used in the media tool, it will not upload or insert anything at all.
It seems that this JavaScript demo provided by TinyMCE has a heavy interaction with the TinyMCE API itself. It has a system of caching and blobs to find the file that TinyMCE uploaded on its own. So pure AJAX-JS knowledge isn't sufficient to tell me how to tell TinyMCE to use my own AJAX upload PHP file. I'd rather just override TinyMCE's upload handler in file_picker_callback so I can use my own PHP upload script to be compatible with the rest of my app.
Goal:
I need a function for file_picker_callback (the file upload button) to use my own AJAX upload handler and preserve the name just as images_upload_handler succeeds in doing.
I am not worried about filename and mimetype validation; I plan to have PHP sanitize and filter later on.
This Question addresses another file uploader and the problem of TinyMCE 4 solutions not always working with TinyMCE 5.
This Question is about image description, and only for images; I want to upload any filetype.
I do not want any dependencies, not even jQuery. Vanilla JS only.
Current Code:
| upload.php :
$temp_file = $_FILES['file']['tmp_name'];
$file_path_dest = 'uploads/'.$_FILES['file']['name'];
move_uploaded_file($temp_file, $file_path_dest);
$json_file_is_here = json_encode(array('filepath' => $file_path_dest));
echo $json_file_is_here;
| tinyinit.js :
tinymce.init({
selector: 'textarea',
plugins: [ 'image media imagetools', ],
automatic_uploads: true,
images_reuse_filename: true,
images_upload_url: 'upload.php',
// From #1. Successful AJAX Upload
images_upload_handler: function(fileHere, success, fail) {
var ajax = new XMLHttpRequest();
ajax.withCredentials = false;
ajax.open('post', 'upload.php');
ajax.upload.onprogress = function (e) {
progress(e.loaded / e.total * 100);
};
ajax.onload = function() {
if (ajax.status == 200) {
if ( (!JSON.parse(ajax.responseText))
|| (typeof JSON.parse(ajax.responseText).filepath != 'string') ) {
fail('Invalid: <code>'+ajax.responseText+'</code>');
return;
}
success(JSON.parse(ajax.responseText).filepath);
} else {
fail('Upload error: <code>'+ajax.status+'</code>');
return;
}
};
var fileInfo = new FormData();
fileInfo.append('file', fileHere.blob(), fileHere.filename());
ajax.send(fileInfo);
},
file_browser_callback_types: 'file image media',
file_picker_types: 'file image media',
// From #2. Neither uploads from "media" nor uses my upload handler
file_picker_callback: function(cb, value, meta) {
var input = document.createElement('input');
input.setAttribute('type', 'file');
input.onchange = function() {
var file = this.files[0];
var reader = new FileReader();
reader.onload = function () {
var blobCache = tinymce.activeEditor.editorUpload.blobCache;
var base64 = reader.result.split(',')[1];
var blobInfo = blobCache.create(file.name, file, base64);
blobCache.add(blobInfo);
cb(blobInfo.blobUri(), { title: file.name });
};
reader.readAsDataURL(file);
};
input.click();
}
});
Editing #Aulia's Answer :
file_picker_callback: function (cb, value, meta) {
var input = document.createElement('input');
input.setAttribute('type', 'file');
input.onchange = function () {
var file = this.files[0];
var reader = new FileReader();
// FormData
var fd = new FormData();
var files = file;
fd.append('filetype',meta.filetype);
fd.append("file",files);
var filename = "";
// AJAX
var xhr, formData;
xhr = new XMLHttpRequest();
xhr.withCredentials = false;
xhr.open('POST', '/your-endpoint');
xhr.onload = function() {
var json;
if (xhr.status != 200) {
alert('HTTP Error: ' + xhr.status);
return;
}
json = JSON.parse(xhr.responseText);
if (!json || typeof json.location != 'string') {
alert('Invalid JSON: ' + xhr.responseText);
return;
}
filename = json.location;
reader.onload = function(e) {
cb(filename);
};
reader.readAsDataURL(file);
};
xhr.send(fd);
return
};
input.click();
}
In the configuration you've provided, #2 doesn't have any logic to upload the data to your server. The code from Tiny's documentation you've copied is just for demo purposes and won't allow you to upload files to Tiny's servers.
You will need to setup the file_picker_callback callback to send data similar to images_upload_handler. On your server, you will need to send the URI and title in the response so the following line will be fulfilled:
cb(blobInfo.blobUri(), { title: file.name });
Hope it will helps mate, make your file_picker_callback looks like below codes
file_picker_callback: function (cb, value, meta) {
var input = document.createElement('input');
input.setAttribute('type', 'file');
input.onchange = function () {
var file = this.files[0];
var reader = new FileReader();
// FormData
var fd = new FormData();
var files = file;
fd.append('filetype',meta.filetype);
fd.append("file",files);
var filename = "";
// AJAX
var xhr, formData;
xhr = new XMLHttpRequest();
xhr.withCredentials = false;
xhr.open('POST', '/your-endpoint');
xhr.onload = function() {
var json;
if (xhr.status != 200) {
failure('HTTP Error: ' + xhr.status);
return;
}
json = JSON.parse(xhr.responseText);
if (!json || typeof json.location != 'string') {
failure('Invalid JSON: ' + xhr.responseText);
return;
}
success(json.location);
filename = json.location;
};
xhr.send(fd);
reader.onload = function(e) {
cb(filename);
};
reader.readAsDataURL(file);
return
};
input.click();
},
I'm trying to program a Client, that can record audio data and then send it to a server.
I don't have much experience in front-end development. I was told to use React and so I'm trying to use ReactMediaRecorder (https://github.com/avasthaathraya/react-media-recorder).
render () {
return (
<ReactMediaRecorder
audio
whenStopped={blobUrl=>this.setState({audio: blobUrl })}
render={({startRecording, stopRecording, mediaBlob }) => (
<div>
<button id="recorder" className="button" onClick={startRecording}>Start Recording</button>
<button className="button" onClick={() => {stopRecording();this.upload()}}>Stop Recording</button>
<audio id="player" src={mediaBlob} controls />
</div>
)}
/>
)
}
upload() {
console.log("upload was called with blob " + this.state.audio)
//if (false) {
if (this.state.audio != null) {
console.log("got here, type of audio is " + this.state.audio)
var xhr = new XMLHttpRequest();
var filename = new Date().toISOString();
xhr.onload = function (e) {
if (this.readyState === 4) {
console.log("Server returned: ", e.target.responseText);
}
};
var fd = new FormData();
fd.append("audio_data", this.state.audio, filename);
xhr.open("POST", "http://127.0.0.1:3000", true);
xhr.send(fd);
}
}
At first it seemed very straightforward. But I don't get why I can't send the mediaBlob. The formData.append says, that this.state.audio is not of type Blob. So I checked it's type in the console log, and found out it is of type stringContent. I tried to create a Blob from that by using new Blob() but failed. I also fail to find information of this type.
Does somebody know what to do?
Ok I finally got it. The mistake was, that mediaBlob is actually not blob, but a blob Url. So first we need to load it and then we can send it. I changed my upload function to:
upload(mediaBlob) {
if (this.state.audio != null) {
//load blob
var xhr_get_audio = new XMLHttpRequest();
xhr_get_audio.open('GET', mediaBlob, true);
xhr_get_audio.responseType = 'blob';
xhr_get_audio.onload = function(e) {
if (this.status == 200) {
var blob = this.response;
//send the blob to the server
var xhr_send = new XMLHttpRequest();
var filename = new Date().toISOString();
xhr_get_audio.onload = function (e) {
if (this.readyState === 4) {
console.log("Server returned: ", e.target.responseText);
}
};
var fd = new FormData();
fd.append("audio_data",blob, filename);
xhr_send.open("POST", "http://localhost/uploadAudio",
true);
xhr_send.send(fd);
}
};
xhr_get_audio.send();
}
}
Now it works fine.
I have list of html stored in database, I want to retrieve the data and convert it to pdf and after converting download it with via ajax request.
I tried hands on it but when the pdf get download the downloaded file is empty.
Please what do i need to do?
Thank you.
JS Code
SMSLiTe('click','.export-to-pdf',function(event){
event.preventDefault();
///export note to pdf via ajax
if (typeof notes[0].note.nid !== typeof undefined && notes.length) {
var nid = notes[0].note.nid;
var fd = new FormData();
fd.append('export_to_pdf',true);
fd.append('note_id',nid);
request.open(bigPipe.formMethod.a, 'pdf/pdf');
request.send(fd);
request.onload = function(e){
if (request.readyState == request.DONE && request.status ==200) {
//code here ....download
var data = request.responseText,
blob = new Blob([data]),
a = document.createElement('a'), d = new Date();
a.href = window.URL.createObjectURL(blob);
a.download = d.getTime()+'.pdf'; a.click();
}
}
}else{
sustainScroll(bigPipe.c_w,bigPipe.class.fixed);
var msg = 'Sorry! something gone wrong, please refresh this page and try again.',title = 'Export Failed';
$(bigPipe.document).append(flexibleDialog({content:templateHTML.flexDialog(msg,title,'_2d0',null,'Close',null,0),isClass:'export_to_pdf_failed _2d0',heigt:140,width:600}));jkg();
}
});
PHP Code
if (isset($_POST['note_id'],$_POST['export_to_pdf'])) {
$nid = (int)$_POST['note_id'];
$sql = "SELECT content FROM $notes_table WHERE note_id='{$nid}' LIMIT 1";
$query = mysqli_query($conn,$sql);
if (mysqli_num_rows($query)) {
$row = mysqli_fetch_assoc($query);
$content = $row['content'];
//create PDF file
$mpdf = new mPDF();
$mpdf->WriteHTML($content);
$mpdf->Output(time().'.pdf','D');exit;
}
}
Inspecting the response data returning from MPDF I realized the output data was a blob and since the data was already blob data. I had a clue of changing the responseType of XMLHttpRequest.responseType to blob
and it worked for now.
modified JS:
SMSLiTe('click','.export-to-pdf',function(event){
event.preventDefault();
//set request method
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
var request = new XMLHttpRequest();
} else { // code for IE6, IE5
var request = new ActiveXObject("Microsoft.XMLHTTP");
}
///export note to pdf via ajax
if (typeof notes[0].note.nid !== typeof undefined && notes.length) {
var nid = notes[0].note.nid;
var fd = new FormData();
fd.append('export_to_pdf',true);
fd.append('note_id',nid);
request.open(bigPipe.formMethod.a, 'pdf/pdf');
request.send(fd);
request.responseType = 'blob';//change reponseType before onload
request.onload = function(e){
if (request.readyState == request.DONE && request.status ==200) {
//code here ....download
var data = request.response,
blob = new Blob([data],{type: 'application/pdf'}),
a = document.createElement('a'), d = new Date();
a.href = window.URL.createObjectURL(blob);
a.download = d.getTime()+'.pdf'; a.click();
//console.log(data);
}
}
}else{
sustainScroll(bigPipe.c_w,bigPipe.class.fixed);
var msg = 'Sorry! something gone wrong, please refresh this page and try again.',title = 'Export Failed';
$(bigPipe.document).append(flexibleDialog({content:templateHTML.flexDialog(msg,title,'_2d0',null,'Close',null,0),isClass:'export_to_pdf_failed _2d0',heigt:140,width:600}));jkg();
}
});
PHP Code:
We have to output MPDF as string since we're not appending MPDF to browser;
//create PDF file
$mpdf = new mPDF();
$mpdf->WriteHTML($content);
$output = $mpdf->Output(time().'.pdf','S');//output as string
echo($output); //final result to JS as blob data
I'm looking for some way to upload video via XHR, and video convert, my script in XHR looks like.
var files= $("#camera"+id).prop('files');
var file = files[0];
var cList= files.length;
$("#camera"+id).val('');
$("#textarea"+id).val('');
var fd = new FormData();
fd.append("file", file);
fd.append("name", name);
fd.append("desc", desc);
fd.append('id', id);
var xhr = new XMLHttpRequest();
xhr.open("POST", "addUcChallenge.php", true);
xhr.upload.onprogress = function(e)
{
};
xhr.onload = function()
{
if(this.status == 200)
{
cList = 1;
//alert(xhr.responseText);
};
};
if(cList < 1)
{
}
else
{
xhr.send(fd);
}
When I tried to upload video is happen nothink, and when I wanted return some value of file nothing too, but photos are ok, and second think is that I don't know how to handle with video in PHP ( Upload, convert to flv ) Thank you!
For uploading you can use PlUploader code example (that is used for large file uploading and make sure you have edited the max file uploading size in php.ini file if you are using php in backend) and for conversion you have to use the FFMPEG
I am trying to create a google-chrome-extension that will download an mp3 file. I am trying to use HTML5 blobs and an iframe to trigger a download, but it doesn't seem to be working. Here is my code:
var finalURL = "server1.example.com/u25561664/audio/120774.mp3";
var xhr = new XMLHttpRequest();
xhr.open("GET", finalURL, true);
xhr.setRequestHeader('Content-Type', 'application/octet-stream');
xhr.onreadystatechange = function()
{
if(xhr.readyState == 4 && xhr.status == 200)
{
var bb = new (window.BlobBuilder || window.WebKitBlobBuilder)();
bb.append(xhr.responseText);
var blob = bb.getBlob("application/octet-stream");
var saveas = document.createElement("iframe");
saveas.style.display = "none";
saveas.src = window.webkitURL.createObjectURL(blob);
document.body.appendChild(saveas);
delete xhr;
delete blob;
delete bb;
}
}
xhr.send();
When looked in the console, the blob is created correctly, the settings look right:
size: 15312172
type: "application/octet-stream"
However, when I try the link created by the createObjectURL(),
blob:chrome-extension://dkhkkcnjlmfnnmaobedahgcljonancbe/b6c2e829-c811-4239-bd06-8506a67cab04
I get a blank document and a warning saying
Resource interpreted as Document but
transferred with MIME type
application/octet-stream.
How can get my code to download the file correctly?
The below code worked for me in Google chrome 14.0.835.163:
var finalURL = "http://localhost/Music/123a4.mp3";
var xhr = new XMLHttpRequest();
xhr.overrideMimeType("application/octet-stream");
//xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
xhr.open("GET", finalURL, true);
xhr.responseType = "arraybuffer";
xhr.onload = function() {
var bb = new (window.BlobBuilder || window.WebKitBlobBuilder)();
var res = xhr.response;
if (res){
var byteArray = new Uint8Array(res);
}
bb.append(byteArray.buffer);
var blob = bb.getBlob("application/octet-stream");
var iframe = document.createElement("iframe");
iframe.style.display = "none";
iframe.src = window.webkitURL.createObjectURL(blob);
document.body.appendChild(iframe);
};
xhr.send(null);
I'm not sure, but i think this is your server's trouble. I've just tried your piece of code to download some sample blob of mp3-file and everything went ok. So maybe:
this file doesn't exist on your server
you server outputs wrong mime type for mp3 files