How to pass file information with a xmlhttp request - javascript

I am trying to make a file upload thing for my messaging system.
I use a file input type and I am using javascript to transmit the file name, tmp, ext etc...
This is my javascript :
document.querySelector('#file').addEventListener('change', function(e) {
var file = this.files[0];
var fd = new FormData();
fd.append("file", file);
var xhr = new XMLHttpRequest();
var group_id = document.getElementById('group_id').value;
var fullurl = '../backend/sendvideosandimages.php?id=' + group_id;
xhr.open('POST', fullurl, true);
xhr.onload = function() {
if (this.status == 200) {
};
};
xhr.send(fd);
}, false);
};
The problem is that it says (in the console) that it successfully loads the url BUT my php never receives the file data. My php code in case you need it :
<?php
session_start();
include_once '../backend/messagingfunctions.php';
include_once '../backend/databaseconn.php';
$errors= array();
$file_name = $_FILES['file']['name'];
$file_size = $_FILES['file']['size'];
$file_tmp = $_FILES['file']['tmp_name'];
$file_type = $_FILES['file']['type'];
$file_ext=strtolower(end(explode('.',$file_name)));
$extensions= array("jpeg","jpg","png","mp4","MP4","MOV","PNG","JPG","mov","JPEG");
if(in_array($file_ext,$extensions)=== false){
$errors[]="extension not allowed, please choose a JPEG, PNG or a MP4 file type!";
}
if($file_size > 16777216) {
$errors[]='File size must be at MOST 16 MB!';
}
if(empty($errors)==true) {
move_uploaded_file($file_tmp,'../userfiles/'.$file_name);
$fileplace = '../userfiles/'.$file_name;
if ($fileplace != null) {
if ($file_ext == "mp4" || "mov" || "MOV" || "MP4") {
$date = date("y-m-d h:i:s");
$filetype = "video";
$myId = $_SESSION['user-id'];
$message = $fileplace;
$groupId = mysqli_real_escape_string($conn, $_GET['id']);
addMessage($myId, $groupId, $date, $message, $filetype);
} elseif ($file_ext == "jpg" || "jpeg" || "png" || "PNG" || "JPG" || "JPEG") {
$date = date("y-m-d h:i:s");
$filetype = "image";
$myId = $_SESSION['user-id'];
$message = $fileplace;
$groupId = mysqli_real_escape_string($conn, $_GET['id']);
addMessage($myId, $groupId, $date, $message, $filetype);
}
}
}
Thanks in advance!

Related

php list files in directory and save to disk

I want to list the files in "archives/" and write the decoded array to disk (file name = "archives/events.txt") But what I have doesn't create that file.
xhr.send(data); // gives: Uncaught ReferenceError: data is not defined
What am I doing wrong?
function LISTevents () {
var xhr = new XMLHttpRequest();
xhr.open("POST", "json-events.php");
xhr.onload = function () {
console.log(this.response);
};
xhr.send(data);
return false;
}
json-events.php
<?php
// create list of events files in archives/* on server
$files1 = scandir('archives');
file_put_contents('archives/events.txt', print_r($files1, true));
?>
<?php
function list_contents($dir, $suffix) {
$contents = array();
$dir = realpath($dir);
if (is_dir($dir)) {
$files = scandir($dir);
foreach ($files as $file) {
if ($file != '.' && $file != '..' && $file != 'events.txt') {
if (substr($file, -strlen($suffix)) == $suffix) {
$contents[] = $file;
}
}
}
foreach ($contents as $key => $item) {
if (strlen($item) != 14) {
unset($contents[$key]);}
}
foreach ($contents as $key => $item) {
if (substr($item,0,1) != "2") {
unset($contents[$key]);}
}
}
$contents_json = json_encode($contents);
file_put_contents($dir . '/events.txt', $contents_json);
}
list_contents('archives','.txt');
?>

Limit image upload size

I have a script for uploading images, it works fine but I would like to limit the image size to a maximum of 2 mb, I have tried a few things but without success, I am not one of the best at this so I would be very grateful for some help, follow the code
$(document).ready(function(){
$("#but_upload_w").click(function(){
var fd = new FormData();
var files = $('#file_w')[0].files;
if(files.length > 0 ){
fd.append('file',files[0]);
$.ajax({
url: 'host/profile/upload.php',
type: 'post',
data: fd,
contentType: false,
processData: false,
success: function(response){
if(response != 0){
$("#up-01").attr("value",response);
$("input").show(); // Link img
}else{
alert('failed');
}
},
});
}else{
alert("select");
}
});
});
<?php
if(isset($_FILES['file']['name'])){
$filename = $_FILES['file']['name'];
$location = "upload/".$filename;
$imageFileType = pathinfo($location,PATHINFO_EXTENSION);
$imageFileType = strtolower($imageFileType);
$temp = explode(".", $_FILES["file"]["name"]);
$newfilename = round(microtime(true)) . '.' . end($temp);
$valid_extensions = array("jpg","jpeg","png");
$response = 0;
if(in_array(strtolower($imageFileType), $valid_extensions)) {
if(move_uploaded_file($_FILES["file"]["tmp_name"], "upload/".$newfilename)){
$response = "host/profile/upload/".$newfilename;
}
}
echo $response;
exit;
}
echo 0; ?>
if(isset($_FILES['uploaded_file'])) {
$errors = array();
$maxsize = 2097152;
$acceptable = array(
'application/pdf',
'image/jpeg',
'image/jpg',
'image/gif',
'image/png'
);
if(($_FILES['uploaded_file']['size'] >= $maxsize) || ($_FILES["uploaded_file"]["size"] == 0)) {
$errors[] = 'File too large. File must be less than 2 megabytes.';
}
if(!in_array($_FILES['uploaded_file']['type'], $acceptable)) {
$errors[] = 'Invalid file type. Only PDF, JPG, GIF and PNG types are accepted.';
}
if(count($errors) === 0) {
move_uploaded_file($_FILES['uploaded_file']['tmpname'], '/store/to/location.file');
} else {
foreach($errors as $error) {
echo '<script>alert("'.$error.'");</script>';
}
die(); //Ensure no more processing is done
}
}
Look into the docs for move_uploaded_file() for more information.

i want to save or download an image from blob url or data

im doing a paste event from clipboard, it creates a blob url. Now i dont how to save or get the file. How can i save it to my computer? I think im totally wrong in getting the blob in my php. im getting it as a string then trying to save it
This is my code for creating the blob
<?php
if( isset( $_FILES['file'] ) ) {
$file_contents = file_get_contents( $_FILES['file']['tmp_name'] );
header("Content-Type: " . $_FILES['file']['type'] );
die($file_contents);
}
else {
header("HTTP/1.1 400 Bad Request");
}
print_r($_FILES);
?>
<script type="text/javascript">
document.onpaste = function (e) {
var items = e.clipboardData.items;
var files = [];
for( var i = 0, len = items.length; i < len; ++i ) {
var item = items[i];
if( item.kind === "file" ) {
submitFileForm(item.getAsFile(), "paste");
}
}
};
function submitFileForm(file, type) {
var extension = file.type.match(/\/([a-z0-9]+)/i)[1].toLowerCase();
var formData = new FormData();
formData.append('file', file, "image_file");
formData.append('extension', extension );
formData.append("mimetype", file.type );
formData.append('submission-type', type);
var xhr = new XMLHttpRequest();
xhr.responseType = "blob";
xhr.open('POST', '<?php echo basename(__FILE__); ?>');
xhr.onload = function () {
if (xhr.status == 200) {
var img = new Image();
img.src = (window.URL || window.webkitURL)
.createObjectURL( xhr.response );
document.getElementById("nye").appendChild(img);
document.getElementById("nye").style.display = "none" ;
var x = document.getElementById("image");
x.setAttribute("type", "text");
x.setAttribute("value", img.src);
document.getElementById("image").appendChild(x);
}
};
xhr.send(formData);
}
</script>
This is my code that's save to my computer, it runs but i juts recive a blank jpg file
<?php
$data = $_POST['url'];
$filePath = $uploadDir . $name;
$contents_split = explode(',', $data);
$encoded = $contents_split[count($contents_split)-1];
$decoded = "";
for ($i=0; $i < ceil(strlen($encoded)/256); $i++) {
$decoded = $decoded . base64_decode(substr($encoded,$i*256,256));
}
$fp = fopen('sample23.jpg', 'w');
fwrite($fp, $decoded);
fclose($fp);
?>
it saves but i think the file is blank.

how to write to database after javascript client side photo resize and upload

I have found a script online which resizes an image client side and then uploads the image to server. This works fine but what I need is to write the image name to mysql database. I know how to do it, but its not working and I think it has something to do with the fact that the script runs client side.
Can anyone look at the following and see where to put the mysql statement. Or if there is a better way of doing it altogether.
upload-form.php
<script>
function uploadphoto()
{
if (window.File && window.FileReader && window.FileList && window.Blob)
{
var files = document.getElementById('filesToUpload').files;
for(var i = 0; i < files.length; i++)
{
resizeAndUpload(files[i]);
}
}
else
{
alert('The File APIs are not fully supported in this browser.');
}
}
function resizeAndUpload(file)
{
var reader = new FileReader();
reader.onloadend = function()
{
var tempImg = new Image();
tempImg.src = reader.result;
tempImg.onload = function()
{
var MAX_WIDTH = 695;
var MAX_HEIGHT = 470;
var tempW = tempImg.width;
var tempH = tempImg.height;
if (tempW > tempH)
{
if (tempW > MAX_WIDTH)
{
tempH *= MAX_WIDTH / tempW;
tempW = MAX_WIDTH;
}
}
else
{
if (tempH > MAX_HEIGHT)
{
tempW *= MAX_HEIGHT / tempH;
tempH = MAX_HEIGHT;
}
}
var canvas = document.createElement('canvas');
canvas.width = tempW;
canvas.height = tempH;
var ctx = canvas.getContext("2d");
ctx.drawImage(this, 0, 0, tempW, tempH);
var dataURL = canvas.toDataURL("image/jpeg");
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(ev)
{
document.getElementById('filesInfo').innerHTML = 'Done!';
};
xhr.open('POST', 'upload-resized-photo.php', true);
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
var data = 'image=' + dataURL;
xhr.send(data);
}
}
reader.readAsDataURL(file);
}
</script>
<form enctype="multipart/form-data" method="post" onsubmit="uploadphoto()">
<div class="row">
<label for="fileToUpload">Select Files to Upload</label><br />
<input type="file" name="filesToUpload[]" id="filesToUpload" multiple="multiple" />
<output id="filesInfo"></output>
</div>
<div class="row">
<input type="submit" value="Upload" />
</div>
</form>
upload-resized-photo.php
<?php
if ($_POST)
{
define('UPLOAD_DIR', 'uploads/');
$img = $_POST['image'];
$img = str_replace('data:image/jpeg;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = UPLOAD_DIR . uniqid() . '.jpg';
$success = file_put_contents($file, $data);
// I did have the mysql insert here but it didnt even execute. Think it is due to xhr.open post method.
}
?>
I test the following code on my computer:
if ($_POST)
{
define('UPLOAD_DIR', 'uploads/');
$img = $_POST['image'];
$img = str_replace('data:image/jpeg;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = UPLOAD_DIR . uniqid() . '.jpg';
$success = file_put_contents($file, $data);
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO images (image_name)
VALUES ('{$file}')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
check your folder permissions, see the following images (Mysql + Files)
This function check all input[type=file]
var _validFileExtensions = [".jpg", ".jpeg", ".bmp", ".gif", ".png"];
function Validate(oForm) {
var arrInputs = oForm.getElementsByTagName("input");
for (var i = 0; i < arrInputs.length; i++) {
var oInput = arrInputs[i];
if (oInput.type == "file") {
var sFileName = oInput.value;
if (sFileName.length > 0) {
var blnValid = false;
for (var j = 0; j < _validFileExtensions.length; j++) {
var sCurExtension = _validFileExtensions[j];
if (sFileName.substr(sFileName.length - sCurExtension.length, sCurExtension.length).toLowerCase() == sCurExtension.toLowerCase()) {
blnValid = true;
break;
}
}
if (!blnValid) {
alert("Sorry, " + sFileName + " is invalid, allowed extensions are: " + _validFileExtensions.join(", "));
return false;
}
}
}
}
return true;
}
you should call that function in:
function uploadphoto(oForm)
{
if(!Validate(oForm)){
return false;
}
if (window.File && window.FileReader && window.FileList && window.Blob)
{
var files = document.getElementById('filesToUpload').files;
for(var i = 0; i < files.length; i++)
{
resizeAndUpload(files[i]);
}
}
else
{
alert('The File APIs are not fully supported in this browser.');
}
return false;
}
and in your form pass the form as parameter:
<form enctype="multipart/form-data" method="post" onsubmit="return uploadphoto(this)">
Good luck

Send $_POST[] and $_FILES[] in same Ajax call

I am working on an image upload post part of my site and I am struggeling to be able to upload the image with the date. I am sending the date via $_POST and the files for the images in $_FILES.
Here is my code (Javascript):
(function post_image_content() {
var input = document.getElementById("images"),
formdata = false;
function showUploadedItem (source) {
var list = document.getElementById("image-list"),
li = document.createElement("li"),
img = document.createElement("img");
img.src = source;
li.appendChild(img);
list.appendChild(li);
}
if (window.FormData) {
formdata = new FormData();
document.getElementById("btn").style.display = "none";
}
input.addEventListener("change", function (evt) {
var data = '';
date = document.getElementById('image_date').value;
if(date == ''){
alert('Please select a date!');
return 0;
} else {
data = 'date='+date;
}
document.getElementById("response").innerHTML = "Uploading . . ."
var i = 0, len = this.files.length, img, reader, file;
for ( ; i < len; i++ ) {
file = this.files[i];
if (!!file.type.match(/image.*/)) {
if ( window.FileReader ) {
reader = new FileReader();
reader.onloadend = function (e) {
showUploadedItem(e.target.result, file.fileName);
};
reader.readAsDataURL(file);
}
if (formdata) {
formdata.append("images[]", file);
}
}
}
if (formdata) {
$.ajax({
url: "submit_image.php",
type: "POST",
data: formdata + ' ' + data,
processData: false,
contentType: false,
success: function (res) {
$('#images').show();
document.getElementById("response").innerHTML = res;
hideImageUpload();
}
});
}
}, false);
}());
function hideImageUpload(){
$('#image_upload_form').hide(250);
//$('#response').hide(250);
$('#image-list').hide(250);
}
And the PHP:
<?php
require_once 'core/init.php';
$user = new User();
$errors = $_FILES["images"]["error"];
$date = $_POST['date'];
$date = explode("/", $date);
$newdate = $date[2] + '-' + $date[0] + '-' + $date[1];
foreach ($errors as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$name = $_FILES["images"]["name"][$key];
//$ext = pathinfo($name, PATHINFO_EXTENSION);
$name = explode("_", $name);
$imagename='';
foreach($name as $letter){
$imagename .= $letter;
}
move_uploaded_file( $_FILES["images"]["tmp_name"][$key], "images/uploads/" . $user->data()->id . '_' . $imagename);
$user->create('photos', array(
'osid' => $user->data()->id,
'user' => $user->data()->username,
'gallery' => 'Uploads',
'filename' => "images/uploads/" . $user->data()->id . '_' . $imagename,
'date' => $newdate
));
}
}
echo "<h2>Successfully Uploaded Images</h2>";
I am new to web development, and I am using PDO to enter into database.
Wait... data: formdata + ' ' + data, It is slightly confusing. You add FormData object and string containing url-encoded data.
Append date value to your formdata object: formdata.append('date', date). After this, send AJAX query with data: formdata, only.
But there may be more errors.
For debugging, use Chrome developer tools. You can use debugger and console.log(something) for breakpoint and printing your vars. Also, you always can use step-by-step debugging.

Categories

Resources