Limit image upload size - javascript

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.

Related

How to pass file information with a xmlhttp request

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!

Codeigniter jquery not working inside AJAX file upload

I have an AJAX file upload code in codeigniter. The Issue is that I changed the simple form submit to file submit. But After that, JQUERY has stopped working. The response is coming success, but at the same time, ajax error function is called. I don't know what's wrong with my code.
This is my controller.
public function ajax_add() {
$this->_validate();
$config = [
'upload_path' => './assets/game_images/',
'allowed_types' => 'gif|png|jpg|jpeg'
];
$this->load->library('upload', $config);
if ($this->upload->do_upload('image')) {
$file = $this->upload->data();
$file_name = $file['file_name'];
if ($file_name == '') {
$data['error_string'][] = 'Please upload an image.';
$data['status'] = FALSE;
echo json_encode($data);
exit();
}
} else {
$data['inputerror'][] = 'image';
$data['error_string'][] = $this->upload->display_errors();
$data['status'] = FALSE;
echo json_encode($data);
exit();
}
$data = array(
'title' => $this->input->post('title'),
'iframe' => $this->input->post('iframe'),
'status' => $this->input->post('status'),
'category_id' => $this->input->post('category_id'),
//'image' => $file_name
);
$insert = $this->game->save($data);
echo json_encode(array("status" => TRUE));
}
private function _validate() {
$data = array();
$data['error_string'] = array();
$data['inputerror'] = array();
$data['status'] = TRUE;
if ($this->input->post('title') == '') {
$data['inputerror'][] = 'title';
$data['error_string'][] = 'Game Title is required';
$data['status'] = FALSE;
}
if ($this->input->post('iframe') == '') {
$data['inputerror'][] = 'iframe';
$data['error_string'][] = 'Game Iframe is required';
$data['status'] = FALSE;
}
if ($this->input->post('status') == '') {
$data['inputerror'][] = 'status';
$data['error_string'][] = 'Status is required';
$data['status'] = FALSE;
}
if ($this->input->post('category_id') == '') {
$data['inputerror'][] = 'category_id';
$data['error_string'][] = 'Please select category';
$data['status'] = FALSE;
}
if ($data['status'] === FALSE) {
echo json_encode($data);
exit();
}
}
And this is my HTML
if (save_method == 'add') {
url = "<?php echo site_url('game/ajax_add') ?>";
} else {
url = "<?php echo site_url('game/ajax_update') ?>";
}
var formData = new FormData($('#form')[0]);
$.ajax({
url: url,
type: 'JSON',
data: formData,
async: false,
success: function (data)
{
if (data.status) //if success close modal and reload ajax table
{
$('#modal_form').modal('hide');
reload_table();
} else
{
for (var i = 0; i < data.inputerror.length; i++)
{
$('[name="' + data.inputerror[i] + '"]').parent().parent().addClass('has-error'); //select parent twice to select div form-group class and add has-error class
$('[name="' + data.inputerror[i] + '"]').next().text(data.error_string[i]); //select span help-block class set text error string
}
}
$('#btnSave').text('save'); //change button text
$('#btnSave').attr('disabled', false); //set button enable
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error adding / update data');
$('#btnSave').text('save'); //change button text
$('#btnSave').attr('disabled', false); //set button enable
},
cache: false,
contentType: false,
processData: false
});
$.ajax({
type: 'POST',
url: url,
dataType: 'JSON',
contentType: 'application/json; charset=utf-8'
})

Passing path to php returns undefined

i am trying to pass a path to a php script and the script is supposed to then return all image files in that path in a array but all i keep getting is undefined error, can someone help please.
function LoadGallery(dir_path) {
$.ajax({
type: 'POST',
url: "getimages.php",
traditional: true,
data:{ path : dir_path},
type: "json",
success: function(data){
alert(data[0]);
// $("#image-container").val(data[0]);
}
});
}
PHP SCRIPT getimages:
<?php
if(isset($_POST['path'])){
$dir = $_POST['path'];
$img = array();
if (is_dir($dir)) {
if ($hnd = opendir($dir)) {
while (false !== ($file = readdir($hnd))) {
if ($file != "." && $file != "..") {
$img[] = $file;
}
}
closedir($hnd);
}
}
return $img;
}
?>
change your php code to return json with result.
<?php
if(isset($_POST['path'])){
$dir = $_POST['path'];
$img = array();
if (is_dir($dir)) {
if ($hnd = opendir($dir)) {
while (false !== ($file = readdir($hnd))) {
if ($file != "." && $file != "..") {
$img[] = $file;
}
}
closedir($hnd);
}
}
echo json_encode($img);
}
?>

Save base64 images with Ajax and Javascript

I'm trying to save/upload images with base64 decode via ajax and FileReader. Photos are displaying but no saving on specify destination. Can anybody help?
The code:
HTML
<input type="file" id="choose" multiple="multiple" />
JS
function readImage(file) {
var reader = new FileReader();
var image = new Image();
reader.readAsDataURL(file);
reader.onload = function(_file) {
image.src = _file.target.result;
image.onload = function() {
var w = this.width,
h = this.height,
t = file.type,
n = file.name,
s = ~~(file.size/1024) +'KB';
$('#uploadPreview').append('<img src="'+ this.src +'"><br>');
};
image.onerror= function() {
alert('Invalid file type: '+ file.type);
};
};
}
$("#choose").change(function (e) {
if (this.disabled) return alert('File upload not supported!');
var F = this.files;
if (F && F[0]) for(var i=0; i<F.length; i++) readImage( F[i] );
$.each(this.files, function(index, file) {
$.ajax({
url: "upload.php",
type: 'POST',
data: {filename: file.filename, data: file.data},
success: function(data, status, xhr) {}
});
});
files = [];
});
PHP
<?php
function uploadimg() {
$error = false;
//if ( ! function_exists( 'wp_handle_upload' ) ) require_once( ABSPATH . 'wp-admin/includes/file.php' );
//$upload_overrides = array( 'test_form' => false );
$images=array();
$a=0;
unset ($_POST['action']);
foreach($_POST as $basefile){
$upload_dir = wp_upload_dir();
$upload_path = str_replace( '/', DIRECTORY_SEPARATOR, $upload_dir['path'] ) . DIRECTORY_SEPARATOR;
$base64_string = $basefile;
echo $basefile;
$base64_string = preg_replace( '/data:image\/.*;base64,/', '', $base64_string );
$decoded_string= base64_decode($base64_string); // 0 bytes written in fwrite
$source = imagecreatefromstring($decoded_string); // 0 bytes written in fwrite
$output_file = $upload_path.'myfilef'.$a.'.jpg';
$images[]=$output_file;
$a++;
$image = fopen( $output_file, 'wb' );
$bytes=fwrite( $image, $source);
echo $bytes;
fclose( $image );
}
echo json_encode($images);
exit;
}
add_action('wp_ajax_uploadimg', 'uploadimg');
add_action('wp_ajax_nopriv_uploadimg', 'uploadimg');
?>
Thx for help.

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