When I upload multiple images I don't get any info in my console, but when I upload one image then that image's info is shown in my console. What I would like is that if I upload more then one image I can get that info so that I can then loop through it and display it in my page through the addThumbnail() function.
When I upload mutliple images this shows up in my Response in my network tab
{"name":"kitten_01.jpg"}{"name":"kitten_05.jpg"}
and my console in blank, but when I upload one image I get
{"name":"kitten_05.jpg"}
and I get this in my console
Object { name: "kitten_05.jpg" }
Here is my main.js
$(document).ready(function(){
var dropZone = document.getElementById('drop-zone');
$(".upload-area").on('drop', function(e){
e.preventDefault();
var files_list = e.originalEvent.dataTransfer.files;
var formData = new FormData();
for(i = 0; i < files_list.length; i++){
formData.append('file[]', files_list[i]);
}
$.ajax({
url:"upload.php",
method:"POST",
data:formData,
contentType:false,
cache: false,
processData: false,
dataType: 'json',
success:function(response){
addThumbnail(response);
}
})
});
dropZone.ondragover = function(e){
return false;
}
dropZone.ondragleave = function(e){
return false;
}
});
function addThumbnail(data){
var len = $("#drop-zone div.thumbnail").length;
var num = Number(len);
num = num + 1;
var name = data.name;
console.log(data);
$("#uploaded-image").append('<div id="thumbnail_'+num+'" class="thumbnail"></div>');
$("#thumbnail_"+num).append('<img src="uploads/'+name+'" width="100%" height="78%">');
}
and this is my upload.php
$allowed = ['png', 'jpg'];
foreach($_FILES['file']['name'] as $key => $name)
{
$temp = $_FILES['file']['tmp_name'][$key];
$ext = explode('.', $name);
$ext = strtolower(end($ext));
$return_arr = array();
if(in_array($ext, $allowed) && move_uploaded_file($temp, 'uploads/'.$name))
{
$return_arr = array("name" => $name);
}
echo json_encode($return_arr);
}
$allowed = ['png', 'jpg'];
$return_arr = array();
foreach($_FILES['file']['name'] as $key => $name)
{
$temp = $_FILES['file']['tmp_name'][$key];
$ext = explode('.', $name);
$ext = strtolower(end($ext));
if(in_array($ext, $allowed) && move_uploaded_file($temp, 'uploads/'.$name))
{
$return_arr = array("name" => $name);
}
}
echo json_encode($return_arr);
Related
First time working with Laravel and a bit confused.
Performing ajax request into controller action and after next request session key I've stored before doesn't exist.
The purpose of this code is to save some set of images and store their names to session for further work..
Session ID's equal in my parent page and ajax request. Application has no user authenticaton yet.
(Upd) Session driver is 'file' by default.
Why session key doesn't save normally?
public function upload(Request $request)
{
$rules = ['photo.*' => 'image|mimes:jpeg,png,jpg|max:2048'];
$validator = Validator::make($request->all(), $rules);
$files = [];
$fileNames = [];
$errors = [];
if ($validator->fails()) {
$errors = ArrayHelper::getFinalValuesRecursive($validator->errors()->messages());
} else {
foreach ($request->file('photo') as $key => $value) {
$imageName = $key . md5(time() . $key) . '.' . $value->getClientOriginalExtension();
$value->move(public_path('uploads'), $imageName);
$fileNames[] = $imageName;
$files[] = '/uploads/' . $imageName;
}
$sessionFiles = [];
if (Session::has('photo')) {
$sessionPhoto = Session::get('photo');
foreach ($sessionPhoto as $value) {
$sessionFiles[] = $value;
}
}
Session::put('photo', array_merge($sessionFiles, $fileNames));
}
Javascript
$(document).ready(function () {
$('#photo').on('change', function () {
var fileData = $('#photo').prop('files');
var formData = new FormData();
for (var i = 0; i < fileData.length; i++) {
formData.append('photo[]', fileData[i]);
}
formData.append("_token", $('input[name="_token"]').attr('value')); //csrf
$.ajax({
url: '{{route('adverts.upload')}}',
dataType: 'text',
cache: false,
contentType: false,
processData: false,
data: formData,
type: 'post',
success: function (response) {
response = $.parseJSON(response);
if (response.errors.length) {
for (var i = 0; i < response.errors.length; i++) {
$('#image_errors')
.append('<div class="invalid-feedback" style="display: block;">' + response.errors[i] + '</div>');
}
} else {
$('#image_errors').html('');
var totalFile = response.files.length;
for (var i = 0; i < totalFile; i++) {
$('#image_preview').append("<img src='" + response.files[i] + "'>");
}
}
}
});
});
});
My ajax request puts files into the directory.
However I receive no response from the PHP file.
I'm using alerts to determine if a response has been received.
Any help would be greatly appreciated.
function doodleSave() {
var canvas = document.getElementById("doodle-canvas");
var canvasData = canvas.toDataURL("image/png");
$.ajax({
url:'test.php',
type:'POST',
data:{ data:canvasData },
success: function(response){
alert(response);
//echo what the server sent back...
}
});
}
<?php
/* AUTOMATED VARIABLES */
$upload_dir = "images/external/doodles/";
$url = md5(uniqid(rand(), true));
$unique_post_id = md5(uniqid(rand(), true));
$timestamp = time();
$nature = "doodle";
$imageUrl = $upload_dir.$url.'.png';
$img = $_POST['data'];
$img = substr($img,strpos($img,",")+1);
$data = base64_decode($img);
$file = $upload_dir . $url . ".png";
$success = file_put_contents($file, $data);
if(!$success) {
exit('unable to upload'); // Prints success and exit the script
} else {
exit($file); // Prints success and exit the script
}
?>
UPDATE:
I success and error to ajax and it comes up as an error.:
function doodleSave() {
var canvas = document.getElementById("doodle-canvas");
var canvasData = canvas.toDataURL("image/png");
$.ajax({
url:'test.php',
type:'POST',
data:{ data:canvasData },
success: function(){
alert('success');
},
error: function(){
alert('failure');
}
});
}
Use json_encode to send data back with AJAX.
<?php
/* AUTOMATED VARIABLES */
$upload_dir = "images/external/doodles/";
$url = md5(uniqid(rand(), true));
$unique_post_id = md5(uniqid(rand(), true));
$timestamp = time();
$nature = "doodle";
$imageUrl = $upload_dir.$url.'.png';
$img = $_POST['data'];
$img = substr($img,strpos($img,",")+1);
$data = base64_decode($img);
$file = $upload_dir . $url . ".png";
$success = file_put_contents($file, $data);
if(!$success) {
echo json_encode(['filename' => false]);
exit(); // Prints success and exit the script
} else {
echo json_encode(['filename' => $file]);
exit();
}
?>
In your AJAX do this
function doodleSave() {
var canvas = document.getElementById("doodle-canvas");
var canvasData = canvas.toDataURL("image/png");
$.ajax({
url:'test.php',
type:'POST',
data:{ data:canvasData },
success: function(response){
var data = JSON.parse(response);
if (data.filename != false) {
alert(data.filename);
}else {
alert('unable to upload');
}
},
error: function(){
alert('failure');
}
});
}
You can also use $.post() which is a shorthand for $.ajax() for POST request.
function doodleSave() {
var canvas = document.getElementById("doodle-canvas");
var canvasData = canvas.toDataURL("image/png");
$.post('test.php', {data: canvasData}, function (response) {
var data = JSON.parse(response);
if (data.filename != false) {
alert(data.filename);
} else {
alert('unable to upload');
}
})
}
You need to replace all spaces with plus sign (+).
Your code with a fix:
<?php
/* AUTOMATED VARIABLES */
$upload_dir = "images/external/doodles/";
$url = md5(uniqid(rand(), true));
$unique_post_id = md5(uniqid(rand(), true));
$timestamp = time();
$nature = "doodle";
$imageUrl = $upload_dir.$url.'.png';
$img = $_POST['data'];
$img = substr($img,strpos($img,",")+1);
$img = str_replace(' ', '+', $img); // Here is a fix
$data = base64_decode($img);
$file = $upload_dir . $url . ".png";
$success = file_put_contents($file, $data);
if(!$success) {
exit('unable to upload'); // Prints success and exit the script
} else {
exit($file); // Prints success and exit the script
}
?>
I get 500 (Internal Server Error) when loading the file inside Codeigniter controller function. What I did is.
PHP:
public function load () {
$dir = "_resources/documents";
$files = scandir($dir);
$ret = array();
foreach($files as $file) {
if($file == "." || $file == "..")
continue;
$filePath = $dir."/".$file;
$data = array(
'name' => $file,
'path' => $filePath,
'size' => filesize($filePath)
);
$ret[] = $data;
}
echo json_encode($ret);
}
and when I inspect the element of the image it becomes
src = _resources/documents/example.jpg
Now in the console, the path becomes
http://localhost/project/document_items/_resources/documents/example.jpg
I wanted it to be
http://localhost/project/_resources/documents/example.jpg
Note that document_items is the name of my controller.
Jquery:
var baseurl = window.location.protocol + "//" + window.location.host + "/project/";
var loadfile = baseurl + 'document_items/load';
$("#fileuploader").uploadFile({
onLoad:function(obj)
{
$.ajax({
cache: false,
url: loadfile,
dataType: "json",
success: function(data)
{
for(var i=0;i<data.length;i++)
{
obj.createProgress(data[i]["name"],data[i]["path"],data[i]["size"]);
}
}
});
}
});
try using the following code snippet:
$this->load->helper('url');
$dir = base_url("_resources/documents");
$files = scandir("_resources/documents");
I have the PHP function:
public function add() {
$image = $this->input->post('image');
$headers = $this->travel_model->getFunction('headers');
//Add new uploaded image
if (!empty($_FILES['img']['name'])) :
//Check uploaded file extension
$file_parts = pathinfo($_FILES['img']['name']);
$ext = $file_parts['extension'];
if($ext == "jpg" || $ext == "jpeg" || $ext == "png") {
$image = md5($_FILES['img']['name']) . "." . $ext;
$img = ROOT.'resources/img/headers/'.$image;
move_uploaded_file($_FILES['img']['tmp_name'], $img);
$result = "passed";
} else {
$result = "error-img-format";
}
else :
$result = "passed";
endif;
//Check if is new added slideshow or editable slideshow
if($result != "error-img-format") {
if($this->input->post('id')) {
$this->headers_model->updateHeaders($image);
} else {
//Check if more than three slides and Delete the last slide
foreach($headers as $key => $hdr) {
if($key >= 2) {
$this->travel_model->deleteFunction($hdr->id, 'slideshows') ;
}
}
$this->headers_model->insertHeaders($image);
}
}
echo $result;
}
Uploaded an img with extensions different than .jpg, .jpeg or .png, PHP displays: error-img-format as it should do
JQuery:
$(document).ready(function () {
$('#add_headers').submit(function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: '/backend/headers/add',
data: $(this).serialize(),
success: function (data) {
alert(data);
}
});
e.preventDefault();
});
});
Alert displays passed, different than PHP does. Can't understand what's the problem..
So I am working on this project where I have to make a photo sharing site, I select the photos and then upload them, send the link via email, and then the person goes on the link and downloads the photos. Everything works great when I have few photos and when not exceeding 100MB of data, when I go beyond that everything becomes unstable.
First of I am using HTML5's FileReader().The logic is the following:
I use FileReader() to transform each photo into a base64 code and every 3 photos transformed I send a 3 photos long base64 string via Ajax to a php file which then transforms the code into photos and uploads them into a folder on the server.
If I have 300 photos selected I do 100 ajax requests.
The first problem if if I exceed ~150MB of data ajax will give me an uncaught exception out of memory error.
The second problem is if I chose over 20-30 files the brower some times gets unresponsive even crashes..
Any suggestions what can I do ? Maybe the whole idea is wrong and I should start somewhere else, please help.
This is the code:
//Forming the inputs
$(document).on("change","#fileUp",function(e){
var file = null;
var files = e.target.files; //FileList object
var picReader = new FileReader();
$(".eventPop").html("");
$(".howMany").html("");
$(".eventPop").show();
$(".eventPop").append('<div class="adding"><img src="../public/cuts/uploading.gif" width="60px"></div>');
countUp = parseInt(countUp) + parseInt(files.length);
for(var i=0; i<=files.length-1; i++){
file = files[i];
var str = file.name.split(".")[0];
//
//var picReader = new FileReader();
if (file.type == "image/jpeg" || file.type == "image/png")
{
picReader.addEventListener("load",function(event){
count++;
var picFile = event.target;
$(".photos").append("<input type='hidden' id='ph"+count+"' get='"+picFile.result+"' /> ");
});
}
else
{
countUp--;
}
picReader.readAsDataURL(file);
}
});
//actual ajax requests
$(document).on('click','.uploadImages',function(){
info[1] = "4hold"+1 + Math.floor(Math.random() * 999999)+"_"+(new Date).getTime();
$.ajax({
type: "POST",
url: "index/loadIntoDB",
dataType:"text",
data: {info: info},
contentType: "application/x-www-form-urlencoded;charset=UTF-8",
success: function(result){
}
});
if (nrConfig > count)
{
nrConfig = count;
}
$(".eventPop").show();
$(".eventPop").html("");
$(".eventPop").append('<div class="adding"><p>Uploading files...'+( (nrConfig/count) * 100).toFixed(0)+'%</p></div>');
for(var i=1; i<=parseInt(nrConfig)+1; i++)
{
if (i == parseInt(nrConfig)+1)
{
info[2] = info[2].substring(2, info[2].length);
uploadImages(nrConfig,1);
}
else
{
//info[0] = i+"-"+info[0];
info[2] = info[2]+"--"+$("#ph"+i+"").attr("get");
}
}
});
function uploadImages(i,d){
info['3'] = i;
info['4'] = d;
$.ajax({
type: "POST",
url: "index/receiveImages",
dataType:"json",
data: {info : info },
beforeSend : function (){
//
},
contentType: "application/x-www-form-urlencoded;charset=UTF-8",
success: function(result){
for(index=result['leftOff']['1']; index <= result['info']['4']-1; index++)
{
if (result[index]['filesize'] < 1000000)
{
result[index]['filesize'] = Math.floor(result[index]['filesize']/1000)+"kb";
$("#ph"+result[index]['id']).append("<div class='filesize'>"+result[index]['filesize']+"</div>");
}
else
{
result[index]['filesize'] = (result[index]['filesize']/1000000).toFixed(2)+"MB";
$("#ph"+result[index]['id']).append("<div class='filesize'>"+result[index]['filesize']+"</div>");
}
if (result[index]['filesize'].length > 0)
{
$("#ph"+result[index]['id']+" .uploading").remove();
$("#ph"+result[index]['id']).append("<img src='layout/cuts/check.png' title='Uploaded' class='done'>");
$("#ph"+result[index]['id']+" .upd").remove();
}
}
$(".eventPop").html("");
$(".eventPop").append('<div class="adding"><p>Uploading files...'+( (result['info'][4]-1)/count * 100).toFixed(0)+'%</p></div>');
if (((result['info'][4]-1)/count * 100).toFixed(0) == 100)
{
setTimeout(function(){
$("progress").remove();
$(".eventPop").html("");
$(".eventPop").append("<div class='adding'>Upload complete!</div>");
setTimeout(function(){
$(".eventPop").html("");
$(".eventPop").append("<div class='adding'><div class='sendPhotos'><form action='#' onsubmit='return false;' method='post' enctype='multipart/form-data'><label>Your email</label><input type='text' class='yemail'/><br/><label>Friend's email</label><input type='text' class='fremail'/><br/><span class='tip'><div class='triangle'></div>You can send photos to multiple friends by typing their e-mail separated by ';'.<br/>Eg. 'thomas#gmail.com ; peter#gmail.com'</span><input type='submit' name='send' class='send' value='Send'></form></div></div>");
},1000);
},1000);
}
if (info[2].length)
{
info[2] = "";
}
if ( (parseInt(result['info']['4'])+parseInt(nrConfig)) >= count )
{
nrConfig = count-result['info']['4']+1;
}
if(result['info']['4'] <= count)
{
for(i=result['info']['4']; i <= parseInt(result['info']['4'])+parseInt(nrConfig); i++)
{
if (i == parseInt(result['info']['4'])+parseInt(nrConfig))
{
info[2] = info[2].substring(2, info[2].length);
uploadImages(nrConfig,result['info']['4']);
}
else
{
info[2] = info[2]+"--"+$("#ph"+i+"").attr("get");
}
}
}
}
});
}
PHP code:
public function receiveImages()
{
$string = strtok($_POST['info'][2],"--");
$currentID = $_POST['info']['4'];
$newArray['info']['3'] = $_POST['info']['3'];
$newArray['leftOff']['1'] = $currentID;
$phAdded = 0;
while($string != false && $phAdded < $_POST['info']['3'])
{
$newArray[$currentID]['id'] = $currentID;
$newArray[$currentID]['filesize'] = $this->saveImages($string,$_POST['info']['1'],$currentID);
$currentID++;
$phAdded++;
$string = strtok("--");
}
$newArray['info']['4'] = $currentID;
echo json_encode($newArray);
}
public function saveImages($base64img = "",$folder = "",$currentID = "")
{
$newArray = array();
if (!is_dir(UPLOAD_DIR.$folder))
{
mkdir(UPLOAD_DIR.$folder,0777);
}
$dir = UPLOAD_DIR.$folder."/";
if (strstr($base64img,'data:image/jpeg;base64,'))
{
$base64img = str_replace('data:image/jpeg;base64,', '', $base64img);
$uniqid = uniqid();
$file = $dir . $uniqid . '.jpg';
$file_name = $uniqid.".jpg";
}
else
{
$base64img = str_replace('data:image/png;base64,', '', $base64img);
$uniqid = uniqid();
$file = $dir . $uniqid . '.png';
$file_name = $uniqid.".png";
}
$data = base64_decode($base64img);
file_put_contents($file, $data);
$size = filesize($file);
if ($size > 1000000)
{
$size = number_format(($size/1000000),2)."MB";
}
else
{
$size = number_format(($size/1000),0)."kb";
}
return filesize($file);
}