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] + "'>");
}
}
}
});
});
});
Related
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);
First I want Apology for my eng.
Second I don't want to use any plugin.
I Want to upload Multiple image and I can do it without ajax, But I want to upload with Ajax.
I Put my Code here.
<form action="{{route('image-upload.store')}}" method="post" enctype="multipart/form-data">
{{csrf_field()}}
<input type="file" id="image-upload" name="image_upload[]" enctype="multipart/form-data" multiple>
<button type="submit">save</button>
</form>
Controller :
if ($request->hasFile('image_upload')) {
$images = $request->file('image_upload');
foreach ($images as $image) {
$randonName = rand(1, 200);
$name = $image->getClientOriginalName();
$storename = $randonName . '_' . $name;
$image->move(public_path('images/test'), $storename);
}
}
return redirect()->back();
Above Code simply upload multiple image without Ajax.
Here Ajax :
html :
<input type="file" id="image-upload" name="image_upload[]" enctype="multipart/form-data" multiple>
Ajax :
$.ajaxSetup({
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}
});
$('#image-upload').change(function () {
event.preventDefault();
let image_upload = new FormData();
let TotalImages = $('#image-upload')[0].files.length; //Total Images
let images = $('#image-upload')[0];
for (let i = 0; i < TotalImages; i++) {
image_upload.append('images', images.files[i]);
}
image_upload.append('TotalImages', TotalImages);
$.ajax({
method: 'POST',
url: '/image-upload',
data: image_upload,
contentType: false,
processData: false,
success: function (images) {
console.log(`ok ${images}`)
},
error: function () {
console.log(`Failed`)
}
})
})
Controller :
if ($request->images) {
$images = $request->images;
$total=$request->TotalImages;
$imagesName = $images->getClientOriginalName();
$randonName = rand(1, 200);
$images->move(public_path('/images/test'), $randonName . '.jpg');
return response()->json($randonName);
}
Now This Code Work Fine but only for one image. I know that I Sould put it Loop and I did But didn't get my Response.
So if anyone can tell me how do it?
Here My Efforts :
if ($request->images) {
$total=$request->TotalImages;
$images = $request->images;
for($j=0; $j<$total;$j++){
$imagesName = $images->getClientOriginalName();
$randonName = rand(1, 200);
$images->move(public_path('/images/test'), $randonName . '.jpg');
}
return response()->json($randonName);
}
if ($request->images) {
$images = $request->images;
foreach ($images as $image) {
$imagesName = $images->getClientOriginalName();
$randonName = rand(1, 200);
$image->move(public_path('/images/test'),$randonName . $imagesName . $randonName . '.jpg');
}
}
this gonna work too this will send array of images so as to get it easily in controller
for (let i = 0; i < TotalImages; i++) {
image_upload.append('images[]', images.files[i]);
}
update your code as follows:
for (let i = 0; i < TotalImages; i++) {
image_upload.append('images', images.files[i]);
}
to
for (let i = 0; i < TotalImages; i++) {
image_upload.append('images' + i, images.files[i]);
}
this should help you to submit multiple images.
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 this script that will upload multiple files and it will be retrieve by the controller.
Question
How can I put another data in the data: section in the AJAX request for example like this:
data: data + '&reference='+$('#ref').val(),
controller
function insertAttachment() {
$i = 0;
$referenceNo = $this->input->post('reference');
if(!isset($_FILES[$i]) ) {
}
else {
$x = $_FILES[$i]['name'];
$xx = explode('.', $x);
$config['upload_path'] = 'MRS-files\Upload_files';
$config['allowed_types'] = 'xls|doc|jpg|png|gif|pdf';
$this->load->library('upload',$config);
for($i; $i <= 4; $i++) {
$counter = $_FILES;
while ( $i <= count($counter) ) {
$x = $_FILES[$i]['name'];
$xx=explode(".", $x);
$config['file_name']= 'IT2015' .'('. ($i+1) .').'. $xx[1];
$this->upload->initialize($config);
$_FILES['up']['name'] = $_FILES[$i]['name'];
$_FILES['up']['tmp_name'] = $_FILES[$i]['tmp_name'];
$_FILES['up']['type'] = $_FILES[$i]['type'];
$_FILES['up']['size'] = $_FILES[$i]['size'];
if ( ! $this->upload->do_upload('up')) {
//error on uploading
echo str_replace('','',$this->upload->display_errors()); //temporary commented no use cause of redirect to homepage
//$this->cancelREC();
exit();
}
else {
$data = array('upload_data' => $this->upload->data());
$this->edit_development_model->insertonAttachments($data['upload_data'] , $referenceNo);
$i++;
}
}
}
}
}
Here is the script:
function EditUploadImage() {
var data = new FormData($('input[name^="edit_files"]'));
jQuery.each($('input[name^="edit_files"]')[0].files, function(i, file) {
data.append(i, file);
});
$.ajax ({
type: 'POST',
data: data,
url: 'mis.php/edit_development_detailsControl/updateRequest',
cache: false,
contentType: false,
processData: false,
success: function(data) {
alert(data);
//messagealert("Success","You're Request have been save successfully");
}
});
}
Hope this one help you.
var fd = new FormData();
var file_data = $('input[type="file"]')[0].files; // for multiple files
for(var i = 0;i<file_data.length;i++){
fd.append("file_"+i, file_data[i]);
}
var other_data = $('form').serializeArray();
$.each(other_data,function(key,input){
fd.append(input.name,input.value);
});
$.ajax({
url: 'test.php',
data: fd,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
console.log(data);
}
});
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);
}