Unable to POST video file input using JS FormData object - javascript

I actually did a lot of research and tried different ways to upload a video file using JQuery's $.ajax() and FormData. I am using an updated version of Chrome and Firefox and aware that uploading of file using $.ajax() is possible for jQuery 1.6 and up. Right now I'm using jQuery-3.3.1.js
For whatever reason, I still can't make it work. I am getting an empty data when I echo $_FILES['myFile']['name'];
view.php
<div class="modal_body">
<form class="container_UserInfo" id="modalForm_uploadVideo">
<label class="modal_label" id="modalLbl_browseVideo">
Select Video
<input type="file" name="myFile" class="modalbtn_browseFiles" id="modalBtn_choose_video_file" value="Select Video" accept="video/*"/><br>
</label>
</form>
</div>
<button class="btn_modalFooter" id="modalBtn_uploadVideo_upload" name="modalBtnName_uploadVideo_upload">
Upload
</button>
view.js
$('#modalBtn_uploadVideo_upload').on('click',function(event){
if(hasInputFileLoaded()){
uploadVideo();
}else{
alert("No file input.");
}
});
function uploadVideo() {
var formData = new FormData();
formData.append('file', $('#modalBtn_choose_video_file')[0].files[0]);
console.log($('#modalBtn_choose_video_file')[0].files[0]); // console displays the selected file info.
$.ajax({
url: 'controller/upload_video.php',
type: 'POST',
data: formData,
processData: false, // tells jQuery not to process the data
contentType: false, // tells jQuery not to set contentType
success: function (data) {
console.log(data);
alert(data);
},
error: function (x, e) {
if (x.status == 0) {
alert('You are offline!!\n Please Check Your Network.');
} else if (x.status == 404) {
alert('Requested URL not found.');
} else if (x.status == 500) {
alert('Internal Server Error.');
} else if (e == 'parsererror') {
alert('Error.\nParsing JSON Request failed.');
} else if (e == 'timeout') {
alert('Request Time out.');
} else {
alert('Unknown Error.\n' + x.responseText);
}
}
});
}
upload_video.php
$myFile = $_FILES['myFile']['name'];
echo "myFile: " . $myFile;
echo "myFile: " . $myFile; displays:
myFile:
This line:
console.log($('#modalBtn_choose_video_file')[0].files[0]); // console displays the selected file info.
shows me the information of the file that was selected and I'm sure it's not empty.
I dont know what's missing. It's able to pick up and run the upload_video.php script but gets nothing in $_FILES[]
I'd like to reiterate that the <form> is contained within a modal div. I don't know if it has anything to do with the problem.
Please help. I'd appreciate any suggestion.
Thank you.
**** EDIT ******
This is what I'm getting in XHR->Headers->Request Payload of Google's Developer Tools.
Request Payload
------WebKitFormBoundarybqKoBuiQ9WumYuTo
Content-Disposition: form-data; name="file"; filename="How to Configure Nginx VirtualHost in Ubuntu.mp4"
Content-Type: video/mp4
And for Request Headers
Accept: */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Connection: keep-alive
Content-Length: 20360818
Content-Type: multipart/form-data; boundary=----WebKitFormBoundarybqKoBuiQ9WumYuTo
Cookie: PHPSESSID=q669bu6jqodkpqpvu2hructsm7
Host: localhost
Origin: http://localhost
Referer: http://localhost/cai/landingpage.php
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36
X-Requested-With: XMLHttpRequest
I've added the enctype="multipart/form-data" method="post" as suggested and var_dump($_FILES); and var_dump($_POST) but keep getting
NULL or array(0){}
I also replaced myFile with file in $_FILES[][]
$myFile = $_FILES['file']['name'];
echo "myFile: " . $myFile;
but did nothing to fix my problem.
What other troubleshooting can I do?
******* end of edit *******

You're sending the file data in the file property, not myFile, so your PHP should be changed to this:
$myFile = $_FILES['file']['name']; // note 'file' here
echo "myFile: " . $myFile;

Related

Local image upload using TinyMCE editor and ExpressJS

I'm running application on my website and for some articles and reviews im using TinyMCE editor. Works perfectly, storing to DB also works.
But i have a need to add local images to articles and upon submitting a form i want to save them to dynamic location on server (based from where i save).
Can i even do this using expressJS and tinyMce editor?
I've tried setting needed stuff in tinymce.init method, I even have upload section when selecting Image in TinyMce UI, but as soon as i select image, i'm getting HTTP error 404. What i did to solve this, is to create POST route in express JS where i suppose i end up in, but i have no idea what i'm doing.
This is my TinyMCE init:
tinymce.init({
selector: '#tinySelector',
plugins: 'advlist autolink link code image lists charmap print preview textcolor media',
toolbar: 'undo redo | image code',
relative_urls: true,
document_base_url: 'http://www.example.com/',
images_upload_url: '/upload.php',
images_upload_hand: function (blobInfo, success, failure) {
var xhr, formData;
xhr = new XMLHttpRequest();
xhr.withCredentials = false;
xhr.open('POST', '/upload.php');
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);
};
formData = new FormData();
formData.append('file', blobInfo.blob(), blobInfo.filename());
xhr.send(formData);
}
});
Express route:
router.post('/upload.php', ensureAuthenticated, (req, res) => {
console.log('testis');
});
Php file:
<?php
/***************************************************
* Only these origins are allowed to upload images *
***************************************************/
$accepted_origins = array("http://localhost", "http://192.168.1.1", "http://example.com");
/*********************************************
* Change this line to set the upload folder *
*********************************************/
$imageFolder = "/public/tinyImages/";
reset ($_FILES);
$temp = current($_FILES);
if (is_uploaded_file($temp['tmp_name'])){
if (isset($_SERVER['HTTP_ORIGIN'])) {
// same-origin requests won't set an origin. If the origin is set, it must be valid.
if (in_array($_SERVER['HTTP_ORIGIN'], $accepted_origins)) {
header('Access-Control-Allow-Origin: ' . $_SERVER['HTTP_ORIGIN']);
} else {
header("HTTP/1.1 403 Origin Denied");
return;
}
}
/*
If your script needs to receive cookies, set images_upload_credentials : true in
the configuration and enable the following two headers.
*/
// header('Access-Control-Allow-Credentials: true');
// header('P3P: CP="There is no P3P policy."');
// Sanitize input
if (preg_match("/([^\w\s\d\-_~,;:\[\]\(\).])|([\.]{2,})/", $temp['name'])) {
header("HTTP/1.1 400 Invalid file name.");
return;
}
// Verify extension
if (!in_array(strtolower(pathinfo($temp['name'], PATHINFO_EXTENSION)), array("gif", "jpg", "png"))) {
header("HTTP/1.1 400 Invalid extension.");
return;
}
// Accept upload if there was no origin, or if it is an accepted origin
$filetowrite = $imageFolder . $temp['name'];
move_uploaded_file($temp['tmp_name'], $filetowrite);
// Respond to the successful upload with JSON.
// Use a location key to specify the path to the saved image resource.
// { location : '/your/uploaded/image/file'}
echo json_encode(array('location' => $filetowrite));
} else {
// Notify editor that the upload failed
header("HTTP/1.1 500 Server Error");
}
?>
I expect to select a file, see it in tinyMce editor, upon submitting saving image for start to some predefined path.

Checking if a m3u8 URL is broken using Javascript

I am using the following code to determine if an m3u8 URL is broken or not. I test with two different URLs, one that is online and one that is offline. For both cases, my javascript function doesn't alert me that file is found or not and firefox debugs doesn't give me any error but status variable always shows 0. Could anyone tell me what I am doing wrong here?
Edit:
for offline url i get this header response(in httpfox developer tool) :HTTP/1.1 404 Not Found
for online url i get this header response(in httpfox developer tool) :HTTP/1.1 200 OK
Code:
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
function testFunction() {
//m="http://someothersite.com/offline.m3u8";
m="http://somesite.com/workingfile.m3u8";
//now we checking if the file exist
UrlExists(m, function(status){
alert('status:'+status);
if(status === 200){
// file was found
alert('file found'+m);
}
else if(status === 404){
// 404 not found
alert('file not found'+m);
}
});
function UrlExists(url, cb){
jQuery.ajax({
url: url,
dataType: 'text',
type: 'GET',
complete: function(xhr){
alert(+xhr.status);
if(typeof cb === 'function')
cb.apply(this, [xhr.status]);
}
});
}
}// end of main
</script>
</head>
<body>
<button onclick="testFunction()">Click me</button>
</html>
This will not work if you are using external URL's as CORS (Cross-origin resource sharing) will kick in and will stop you as you are not on the same domain.
Working version: local files only
UrlExists('/path/file.php', function(status){
if(status === 200){
alert('file found');
}
else if(status === 404){
alert('file not found');
}
});
Unfortunately, there isnt a valid way of doing this through Javascript. However, you can conduct this through backend functionality e.g. PHP
$file = 'http://www.othername.com/somefile.jpg';
$file_headers = #get_headers($file);
if($file_headers[0] == 'HTTP/1.1 404 Not Found') {
$exists = false;
}
else {
$exists = true;
}
If you build this into a php function and then use your Ajax functionality to pass the URL through to the PHP for validation, and then return back a response - it should work.
Edit: Curl Example
$mainUrl = curl_init($url);
curl_setopt($mainUrl, CURLOPT_RETURNTRANSFER, TRUE);
$response = curl_exec($mainUrl);
$httpCode = curl_getinfo($mainUrl, CURLINFO_HTTP_CODE);
if($httpCode == 404) {
echo "404 Error";
}else if($httpCode == 200){
echo "200 Error";
}else{
echo "all good - sort off...";
}
curl_close($mainUrl);
Here is the Curl option - Now the way i would do it (and i really had to do it...) is looping through each and every single URL on the page (in js) and sending it as an object to PHP (through Ajax). With PHP, i would use the above CURL functionality to confirm which ones are broken (either with a 1 or 0) and then send a response back.

how to access popup's cookie in chrome extension development?

I need to post some data to a django server using popup's js.because of the csrf, I should post data with csrftoken in cookie, how can i get the the value in the cookie. I have tried the following ways which do not work:
document.cookie
chrome.cookies.get({url: "chrome-extension://igmgfjnbghncmhbobdpjblokohejackc", name: "csrftoken"}, function(cookie){})
request infomation:
Request Method:POST
Status Code:403 FORBIDDEN
Request Headersview source
Accept:*/*
Accept-Encoding:gzip, deflate
Accept-Language:zh-CN,zh;q=0.8
Connection:keep-alive
Content-Length:3
Content-Type:application/x-www-form-urlencoded; charset=UTF-8
Cookie:csrftoken=V6OTh2NdwnomqLbkfh24qRwT8C0kESIV
Host:127.0.0.1:8000
Origin:chrome-extension://igmgfjnbghncmhbobdpjblokohejackc
User-Agent:Mozilla/5.0 (iPhone; CPU iPhone OS 8_0 like Mac OS X) AppleWebKit/600.1.3 (KHTML, like Gecko) Version/8.0 Mobile/12A4345d Safari/600.1.4
X-CSRFToken:null
You cannot access the csrftoken cookie from any domain but the one that generated it. So, you have to read the csrftoken when it's generated and save it if you want to use it from your extension.
In my case, when the token was not present, it didn't cause any error, but as soon as I logged in the server, the csrftoken was set, and couldn't retrieve it from any other domain, getting the 403 error on any request that was not generated in the same domain.
To fix it, first, I had to read the cookie from the domain when I logged in and save it to chrome storage. First, I need proper permissions (Note that, where I use background/background.js you could switch to popup/popup.js if needed)
manifest.json
...,
"background": {
"scripts": ["jquery-1.11.1.min.js","background.js"],
"persistent": false
},
"permissions": ["tabs", "<all_urls>", "storage", "webNavigation"],
"content_scripts":[
{
"matches":["yourDomain"],
"js": ["jquery-1.11.1.min.js", "readCSRFToken.js"]
}],...
Now, this small script will read the cookie we need if it's present and send it to our extension. You could check the host name before sending the cookie if you want to be sure that you take the correct CSRF token.
readCSRFToken.js
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
csrftoken = getCookie("csrftoken");
if ( csrftoken ){
chrome.runtime.sendMessage({action:"setCsrfToken", csrftoken:csrftoken}, function(){});
}
In the extension code, we add a listener that will save the csrf token in chrome storage when it's sent by the injected code.
There is also a webNavigation.onComplete that will read the token from storage every time we load a page.
background.js
csrftoken = null;
chrome.webNavigation.onCompleted.addListener(function(details) {
if ( details.frameId == 0 ){
chrome.storage.sync.get(["csrftoken"], function(storage){
csrftoken = storage.csrftoken;
});}
}
);
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
switch ( request.action ){
case "setCsrfToken":{
chrome.storage.sync.set({'csrftoken': request.csrftoken}, function() {});
}
break;
}
});
Finally, we have a csrftoken variable stored that we should be able to use to set the "X-CSRFToken" header to allow our AJAX request to work properly when used from the extension.
...
var headers = {}
if ( csrftoken ) headers["X-CSRFToken"] = csrftoken;
$.ajax({
dataType: 'json',
headers: headers,
...
});
I assume you already followed these steps: https://docs.djangoproject.com/en/1.7/ref/contrib/csrf/#how-to-use-it
I'm not familiar with popup.js but since it's a jquery plugin, this should work for you. An ajax request which puts the csrftoken into the request header:
$.ajax({
dataType: 'json',
headers: {"X-CSRFToken": $.cookie('csrftoken') },
...
}

jquery $.post doesnt sent post data

im trying to make a post request to the server but the jquery doesnt sent any post date.
i already tried to use: (suggestions i found on the web)
var postdata = {'username':username,'password':password,'src':'web'};
instead of
var postdata = 'username=' + username + '&pass=' + password + '&src=web';
this is my jquery code:
var username = $('#uForm_un').val();
var password = $('#uForm_pw').val();
var postdata = 'username=' + username + '&pass=' + password + '&src=web';
console.log(postdata);//output: username=administrator&pass=password&src=web
$.post(
"inc/api/do.login.ajax",
postdata,
function (data) {
console.log(data);//output: a vardump($_POST) wich is empty.
}
);
browser data:
Remote Address:62.***.**.**:80
Request URL:***********/inc/api/do.login.ajax/
Request Method:GET
Status Code:200 OK
Request Headersview source
Accept:*/*
Accept-Encoding:gzip,deflate,sdch
Accept-Language:nl-NL,nl;q=0.8,en-US;q=0.6,en;q=0.4
Cache-Control:no-cache
Connection:keep-alive
Cookie:anonymous=-81523622186; windowtop=100; LanguageId=1; CurrencyId=1; space_history=%7B%221%22%3A%2220%22%7D; eventId=1; OrderId=201424754035; filter_starttime=6%3A00; filter_endtime=12%3A00; _ga=GA1.2.2031844175.1410181977; __atuvc=13%7C37; PHPSESSID=4x1xc4ca4238a0b923820dcc509a6f75849b; filter_display_mode=grid; filter_search=; filter_where=eindhoven; filter_startdate=01/09/2014; filter_enddate=05/09/2014; filter_order=itemdate; filter_dayparts=; filter_distance=100000; filter_categories=; list=%2C2797
Host:********.nl
Pragma:no-cache
Referer:***************/index.php?action=editvisit
User-Agent:Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.103 Safari/537.36
X-Requested-With:XMLHttpRequest
Response Headersview source
Connection:Keep-Alive
Content-Encoding:gzip
Content-Length:156
Content-Type:text/html; charset=utf-8
Date:Thu, 11 Sep 2014 09:15:03 GMT
Keep-Alive:timeout=5, max=88
Server:Apache/2.2.22 (Debian)
Vary:Accept-Encoding
X-Powered-By:PHP/5.4.4-14+deb7u14
EDIT:
now i use this code, but with the same result...
$.post( "inc/api/do.login.ajax",{
username : ""+$('#uForm_un').val()+"",
pass : ""+$('#uForm_pw').val()+"",
src : "web"
}).done(function(data) {
console.log(data);
}, "json" );
Solution:
change this:
inc/api/do.login.ajax
to
inc/api/do.login.ajax/index.php
with a get request it works fine but with a post...
sorry for taking your time and thanks! every answer was usefull!

PHP curl form with no action and js events

I'm trying to use curl to post some data and retrieve it from a website that isn't mine, the websites form doesn't seem to have a form action and the page doesn't reload when you submit the data and there also seems to be some js behind the click of the button.
$url = "http://emonitoring.poczta-polska.pl/#";
$parm = "numer=RR123456789PL";
and here is the curl:
array(
CURLOPT_URL => $url,
CURLOPT_POST => TRUE,
CURLOPT_POSTFIELDS => $parm,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_FOLLOWLOCATION => TRUE
);
I execute and init the curl as expected, just showing the important parts. Here is also the live http headers output:
POST /wssClient.php HTTP/1.1
Host: emonitoring.poczta-polska.pl
Accept: */*
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Content-Type: application/x-www-form-urlencoded
Origin: http://kody.poczta-polska.pl
Referer: http://kody.poczta-polska.pl/
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36
HTTP/1.1 200 OK
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Content-Length: 1215
Content-Type: text/html; charset=UTF-8
Date: Mon, 30 Jun 2014 03:31:59 GMT
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Pragma: no-cache
Server: Apache
X-Cnection: close
At the moment it just shows the page and it doesn't look like that form was submitted, I've also tried putting the url as: "http://emonitoring.poczta-polska.pl/wssClient.php" and just get told to enter the number.
In such cases you go to chrome, hit F12, go to network, submit the form and see what is sent to the server. I see this posted
s:fggsbnqu033gqiipemr50fer56
n:RR123456789PL
l:
If you view source you see
if (jQuery('#numer').val().length == 19) {
var numer = dodajck(jQuery('#numer').val())
} else var numer = jQuery('#numer').val();
jQuery.ajax({
type: 'post',
cache: true,
dataType: 'html',
data: ({
s: 'fggsbnqu033gqiipemr50fer56',
n: numer,
l: ''
}),
url: 'wssClient.php',
The s:.... could mean you need to have a session on their server to be able to call the wssClient - if so, you will need to CURL with sessions
If you can call their server without a session or you have a session before you call you can curl using the parm is n= and not numer= and you need to have calculated the checksum using their function which can easily be translated to PHP
function dodajck(numer) {
// dodatkowe sprawdzenia i określenie wag oraz części numeru, która
// ma zostać zważona
//String wagi;
//String doWazenia;
var wagi = "3131313131313131313";
var doWazenia = String(numer);
// wyliczenie sumy iloczynów waga * cyfra
var suma = 0;
for (var i = 0; i < 19; i++)
suma = suma + Number(doWazenia.substring(i, i + 1)) * Number(wagi.substring(i, i + 1));
// ostateczne sprawdzenia
// przykład numeru 20-cyfrowego
// 00
// 1 - rodzaj?
// 590 -- kraj 590 = PL
// 0773 -- firma 0773 = PP
// 3 -- rodzaj przesyłki
// 12345678 - numer przesyłki
// 9 - CK
// ważone są numery od 1 do 19
var ck = 10 - suma % 10;
if (ck == 10) ck = 0;
return String(numer) + String(ck);
}
The form is submitted via AJAX. To see the exact HTTP request simply fire up the developer tools in Chrome or Firefox (F12). Navigate to the 'Network' tab, and hit the submission button on their website. You should see a request being fired off. If you open it up, you will be able to see everything you need to make the request yourself - URL, Parameters and their format, HTTP header values, etc. - and the response you're supposed to get.
Hope this helps!

Categories

Resources