I'm trying to upload a video with some other parameters via a shared web worker.
Here below I paste de code I'm using:
record.js
function sendVideo(name, path) {
var worker = new SharedWorker("js/upload.js");
worker.port.postMessage([path, name + '.webm', blob]);
// worker.port.start();
worker.port.onmessage = function(e) {
console.log('Message received from worker ' + e.data);
}
}
upload.js
onconnect = function(e) {
var port = e.ports[0];
port.onmessage = function(e) {
var path = e.data[0];
var fileName = e.data[1];
var video = e.data[2];
var request = new XMLHttpRequest();
request.open('POST', 'http://localhost/channel/upload', true);
request.onload = function () {
port.postMessage(request.responseText);
};
request.send('fileName=' + fileName + '&video=' + video);
}
// port.start(); // not necessary since onmessage event handler is being used
}
channel.php
public function upload()
{
$data = file_get_contents('php://input');
// get the video from $data and move it
}
The problem is if my worker send:
request.send('fileName=' + fileName + '&video=' + video);
the content that my php code get is [blob data].
and if my worker send:
request.send('video=' + video);
the content that my php get is the video coded, full of special characters.
My question is how could I get the text and the video like if I had $_FILES in order to process it correctly.
Thanks in advice.
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 am using a third party API to upload a video to that server. Once I have uploaded the video I make a verification call to check if all the file has been uploaded ('verifyUpload()'). If all the file has been uploaded then great, otherwise I resume the upload ('resumeUpload()') from the last byte that was uploaded. The problem that i am having, and I do not understand why, is that my 'resumeUpload()' does not appear to be executing - have i coded this incorrectly?
In the console I can see the following lines executing from resumeUpload():
console.log('vim.resumeUpload() ...');
console.log('stringArgument: ' + stringArgument);
But instead of the line:
xmh.setRequestHeader('Content-Range', stringArgument);
being executed I am seeing :
xmh.setRequestHeader('Content-Range', 'bytes /');
being executed from verifyUpload().
verifyUpload()
// VERIFY UPLOAD (SO FAR)
var verifyUpload = function(){
console.log('verifying upload() ...');
var xmh = new XMLHttpRequest;
xmh.onreadystatechange = function(){
console.log('xmh.readyState111: ' + xmh.readyState);
console.log('xmh.status111: ' + xmh.status);
if(xmh.readyState == xmh.HEADERS_RECEIVED){
console.log('VERIFY RESPONSE HEADERS: ' + xmh.getAllResponseHeaders());
console.log('getResponseHeader(\'Content-Range\')' + xmh.getResponseHeader("Range"));
var range = xmh.getResponseHeader("Range");
var rangeArray = range.split('-');
var bytesUploaded = rangeArray[1];
bytesUploaded = Number(bytesUploaded);
var leftToUpload = vim.vidFileSize-bytesUploaded;
console.log('bytesUploaded: '+bytesUploaded);
console.log('byteLeftToUpload: '+ leftToUpload);
// IF ALL THE FILE HAS BEEN UPLOADED TO THE SERVER
// COMPLETE UPLOAD
if(leftToUpload == 0){
completeVidUpload();
}else{
// NEED TO RESUME UPLOAD FROM WHERE WE LAST LEFT OFF
vim.bytesToUploadFrom = bytesUploaded + 1;
var stringValue = 'bytes '+vim.bytesToUploadFrom+'-'+vim.vidFileSize+'/'+vim.vidFileSize+'';
console.log('stringValue: '+ stringValue);
resumeUpload(stringValue);
}
}
}
xmh.open('PUT', vim.upload_link_secure);
xmh.setRequestHeader('Content-Range', 'bytes */*');
xmh.send();
}
resumeUpload():
// RESUME UPLOAD WHERE LEFT OFF
var resumeUpload = function(stringArgument){
console.log('vim.resumeUpload() ...');
console.log('stringArgument: ' + stringArgument);
var xmh = XMLHttpRequest;
// SET EVENT LISTENERS
// SET EVENT LISTENERS
xmh.upload.addEventListener('progress', uploadProgres, false);
xmh.addEventListener('load', uploadComplete, false);
xmh.addEventListener('error',uploadError, false);
xmh.onreadystatechange = function(){
if(xmh.readyState == xmh.HEADERS_RECEIVED){
console.log('VERIFY RESPONSE HEADERS222: ' + xmh.getAllResponseHeaders());
console.log('getResponseHeader(\'Content-Range\')222' + xmh.getResponseHeader("Range"));
}
}
xmh.open('PUT', vim.upload_link_secure);
xmh.setRequestHeader('Content-Range', stringArgument);
xmh.send();
}
I think you missed new in resumeUpload here:
var xmh = XMLHttpRequest;
I have very new to JS and I have done my research but I guess I'm kind of using the wrong technique or something.
Like in python to make GET request we do:
request_text = requests.get(url).text
I want to do the same thing but using JS i.e. display the content from "http://synd.cricbuzz.com/j2me/1.0/livematches.xml" in the raw(xml) format and I have found this script somewhere but it doesn't work.
<h2>AJAX</h2>
<button type="button" onclick="loadDoc()">Request data</button>
<p id="demo"></p>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("demo").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "http://synd.cricbuzz.com/j2me/1.0/livematches.xml", false);
xhttp.send();
}
</script>
</body>
</html>
I just need the direction on how to do the same i.e. how to send a GET/POST request using JS and render it on a webpage?
When I use
function test(url) {
var req = new XMLHttpRequest();
req.open('GET', url);
req.onload = function() {
var section = document.createElement('section');
var h2 = document.createElement('h2');
h2.textContent = 'Received from ' + url;
section.appendChild(h2);
var pre = document.createElement('pre');
pre.textContent = req.responseText;
section.appendChild(pre);
document.body.appendChild(section);
};
req.onerror = function(evt) {
document.body.insertAdjacentHTML('beforeEnd', '<p>Error requesting ' + url + '.<\/p>');
};
req.send();
}
document.addEventListener('DOMContentLoaded', function() {
test('http://home.arcor.de/martin.honnen/cdtest/test2011060701.xml');
test('http://synd.cricbuzz.com/j2me/1.0/livematches.xml');
},
false);
the first URL works as the server is set up to allow the CORS request for that directory while the second fails as the server does not allow it. So unless you serve your HTML with the script from synd.cricbuzz.com or unless you can change the configuration of synd.cricbuzz.com to allow a CORS request you won't be able to request the XML from that server.
Note also that in modern browsers (current versions of Mozilla, Chrome, Edge) you can use the Promise based fetch method instead of XMLHttpRequest, as shown below. But the same origin policy is not different for fetch, so the same as stated above holds.
function test(url) {
fetch(url).then(function(response) {
if(response.ok) {
response.text().then(function(text) {
var section = document.createElement('section');
var h2 = document.createElement('h2');
h2.textContent = 'Received from ' + url;
section.appendChild(h2);
var pre = document.createElement('pre');
pre.textContent = text;
section.appendChild(pre);
document.body.appendChild(section);
});
}
else {
document.body.insertAdjacentHTML('beforeEnd', '<p>Error requesting ' + url + '; status: ' + response.status + '.<\/p>');
}
})
.catch(function(error) {
document.body.insertAdjacentHTML('beforeEnd', '<p>Error "' + error.message + '" requesting ' + url + '.<\/p>');
});
}
document.addEventListener('DOMContentLoaded', function() {
test('http://home.arcor.de/martin.honnen/cdtest/test2011060701.xml');
test('http://synd.cricbuzz.com/j2me/1.0/livematches.xml');
},
false);
EDIT: Changed win() function and added am image corresponding to it's result.
I am having trouble uploading image to a webserver using phonegap.
This is the code that I have for the app:
var pictureSource; // picture source
var destinationType; // sets the format of returned value
// Wait for Cordova to connect with the device
//
document.addEventListener("deviceready",onDeviceReady,false);
// Cordova is ready to be used!
//
function onDeviceReady() {
pictureSource=navigator.camera.PictureSourceType;
destinationType=navigator.camera.DestinationType;
}
// Called when a photo is successfully retrieved
//
function onPhotoURISuccess(imageURI) {
// Get image handle
//
var largeImage = document.getElementById('largeImage');
// Unhide image elements
//
largeImage.style.display = 'block';
// Show the captured photo
// The inline CSS rules are used to resize the image
//
largeImage.src = imageURI;
var options = new FileUploadOptions();
options.fileKey = "file";
options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1);
options.mimeType="image/jpeg";
var params = new Object();
params.value1 = "test";
params.value2 = "param";
options.params = params;
options.chunkedMode = false;
var ft = new FileTransfer();
ft.upload(imageURI, "http://www.tayabsoomro.me/upload.php", win, fail, options);
}
function win(r){
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
console.log("Sent = " + r.bytesSent);
alert(r.response);
}
function fail(error){
alert("An error occured while uploading image: " + error.code);
}
The code triggers win() function and shows the JSON data of the result when the image is captured so at least it doesn't fail().
And here's an image of what win() function alerts.
and this is what my upload.php looks like:
<?php
print_r($_FILES);
$new_image_name = "myimg.jpg";
move_uploaded_file($_FILES["file"]["tmp_name"], "uploads/".$new_image_name);
?>
Ensure that you have all the appropriate (Read/Write) permissions set to your target folder uploads/ where you try to upload your files.
Hope this helps!.
I'm trying to insert a new user into mysql. I have tried to use jQuery, but it doesn't seem to be working. I tried to use pure javascript, but it's the same. It has no response after I click on the button. What's wrong?
var regBtn = document.getElementById("regBtn");
regBtn.addEventListener("click", submitForm, false);
function submitForm() {
var acR = document.getElementById("ac2");
var pw1 = document.getElementById("pw1");
var shop = document.getElementById("shop");
var http = new XMLHttpRequest();
http.open("POST", "http://xyz.php", true);
http.setRequestHeader("Content-type","application/x-www-form-urlencoded");
var params = "ac=" + acR + "&pw1="+pw1 "&shop="+ shop;
http.send(params);
http.onload = function() {
alert(http.responseText);
};
}
There's a quite a few problems in your JS code, I've tidied it up here and run it locally to a page called xyz.php, so that'll get the AJAX call to work but you'll need to post your PHP code to get any help with your DB queries
var regBtn = document.getElementById("regBtn");
regBtn.addEventListener("click", submitForm, false);
function submitForm() {
var acR = document.getElementById("ac2");
var pw1 = document.getElementById("pw1");
var http = new XMLHttpRequest();
// removed the http:// protocol, assuming you're going for a local AJAX call
http.open("POST", "xyz.php", true);
http.setRequestHeader("Content-type","application/x-www-form-urlencoded");
// get values of the form fields, don't submit the full element
// also added the plus (+) character before the final pw1
var params = "ac=" + acR.value + "&pw1=" + pw1.value;
http.send(params);
http.onload = function() {
alert(http.responseText);
}
}
I've attached a screen shot showing Chrome Dev Tools happily recording successful AJAX requests
Try to use a JQuery post.
var acR = document.getElementById("ac2");
var pw1 = document.getElementById("pw1");
$.post( "xyz.php", { ac: acR, pw1: pw1 })
.done(function( data ) {
alert( "Data inserted: " + data );
});
Backend handles this post and then implement the insert action for example in NodeJs(express)
app.post("/xyz", function(req, res, next) {
var obj = {};
obj[acR] = body.ac;
obj[pw1] = body.pw1;
mysql.insert(obj);
});