Multiple Image Upload using Ajax with Laravel 5.6 - php

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.

Related

Laravel session::has('key') doesn't exist after new request

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] + "'>");
}
}
}
});
});
});

Uploading multiple images with dropzone.js with Laravel

I am using dropzone with laravel to upload multiple images and it works correctly. what I am asking for is I want to upload them at once and then send email to my customer to show him that photos have been uploaded.
Thanks in advance.
<form action="{{route('upload.photos')}}" method="post" enctype="multipart/form-data" class="dropzone" id="dropzoneFileUpload" >
{{csrf_field()}}
<div>
<h3 class="text-center">Upload Multiple Image By Click On Box</h3>
</div>
<div class="fallback">
<input name="file" type="file" multiple />
</div>
</form>
<script type="text/javascript">
Dropzone.options.imageUpload = {
maxFilesize:500,
acceptedFiles: ".jpeg,.jpg,.png,.gif",
autoProcessQueue: false,
uploadMultiple: true,
parallelUploads: 25,
maxFiles: 25
};
</script>
$file = $request->file('file');
$fileName = time().$file->getClientOriginalName();
Storage::disk('local')->put($car_id.'/'.$fileName, File::get($file));
Photo::create([
'photo_name'=>$fileName,
'car_id'=>$car_id
]);
$data = [
'first_name'=>$car->user->first_name,
'last_name'=>$car->user->last_name,
'vin'=>$car->vin,
'model'=>$car->model,
'make' =>$car->make
];
Mail::send('admin.email.send_album_notification',$data,function($message) use($car){
$message->subject('Pictures for Test - Example ');
$message->from('noreply#example .com','Example ');
$message->to($car->user->email,$car->user->full_name);
});
If I share my experience then Create one unique id for every form like
<form>
<input type="hidden" value="{{ uniqid() .'-'. Carbon\Carbon::now()->timestamp }}" name="form-token"/>
<form>
Now you have identification for every form right. Insert it with every image. It is very easy to track every image.
For Example:
Photo::create([
'photo_name'=>$fileName,
'car_id'=>$car_id,
'form_token'=>$request->get('form-token'),
]);
Once you insert that You have form_token column to find all uploaded image at a time. Mean to say suppose your user uploaded 5 images and each image have same token. Now just find that images by token and send into mail.
$photos = Photo::whereFormToken($request->get('form-token'))->get();
$data['photos'] = $photos;
Mail::send('admin.email.send_album_notification',$data,function($message) use($car){
$message->subject('Pictures for Test - Example ');
$message->from('noreply#example .com','Example ');
$message->to($car->user->email,$car->user->full_name);
});
Now your mail view file have photos collection object so you can just print out it. Something like this:
#foreach($photos as $photo_key => $photo_value)
<?php $pathToImage = public_path()."/".$photo_value->image_name; ?>
<img src="{!! $photo_value->embed($pathToImage); !!}" style="max-width: 80%;padding-top: 20px;">
#endforeach
let image_index = 0;
Dropzone.autoDiscover = false;
$(function () {
let feedback_img_upload = new Dropzone('#image_upload', {
paramName: "file",
uploadMultiple: true,
parallelUploads: 5,
maxFilesize: 500,
acceptedFiles: '.jpg, .png, .gif, .pdf, .jpeg',
previewTemplate: document.getElementById('preview').innerHTML,
addRemoveLinks: true,
dictRemoveFile: 'Remove file',
dictFileTooBig: 'Image is larger than 16MB',
timeout: 10000,
url: "/images-save",
init: function () {
this.on("removedfile", function (file) {
let inputObj = $.parseJSON(file['xhr'].response);
$.post({
url: '/images-delete',
data: {id: inputObj.image_name, _token: $('[name="_token"]').val()},
dataType: 'json',
success: function (data) {
if (file.xhr != undefined) {
let imgId = inputObj.file_name;
$('#inquiry_imgfile_' + imgId).remove();
}
return true;
}
});
});
},
});
feedback_img_upload.on("success", function (file, obj) {
if (obj.status == 1) {
image_index++;
$('#inquiry_imgfile_main_div').append('<input class="inquiry_imgfile_upload" id="inquiry_imgfile_' + obj.file_name + '" name="inquiry_imgfile[]" value="" type="hidden"/>');
$("#inquiry_imgfile_" + obj.file_name).val(obj.image_name);
}
});
});
public function store(Request $request)
{
try {
$photos = $request->file('file');
if (!is_array($photos)) {
$photos = [$photos];
}
if (!is_dir($this->photos_path)) {
mkdir($this->photos_path, 0777);
}
$img_names = [];
for ($i = 0; $i < count($photos); $i++) {
try{
$photo = $photos[$i];
$name = date('YmdHisu') . rand(1, 1000000) . $i;
$file_name = $name . rand(1, 1000000);
$resize_name = $file_name . '.' . $photo->getClientOriginalExtension();
$img_names[] = $resize_name;
$photo->move($this->photos_path, $resize_name);
$this->save();
$img = Image::make($photo);
$img->text(' Mysale.lk', 200, 200, function ($font) {
$font->file(public_path('app/OpenSans-Light.ttf'));
$font->size(50);
$font->color('#fdf6e3');
$font->align('center');
$font->valign('top');
});
$img->save($this->photos_path . '/' . $resize_name);
return Response::json([
'image_name' => $resize_name,
"status" => 1,
"file_name" => $file_name
], 200);
exit();
}catch (\Exception $ex){
dd($ex);
}
}
} catch (\Exception $e) {
return Response::json([
"status" => 0
], 401);
exit();
}
}

getting error while uploading image via Ajax

im having trouble in uploading a multiple file by ajax . here is my code.
HTML code:-
<input type="file" id="txtBusinessImage" class="form-control" name="txtBusinessImageName[]" multiple >
<input type="hidden" id="selectBusinessHiddenID" name="selectBusinessHiddenID" value="<?php echo $viewCompanyResult->company_id; ?>">
<input type="button" id="uploadBusinessImg" value="Upload" >
Ajax Code:-
$("#uploadBusinessImg").on("click",function(e)
{
var fd = new FormData();
var file_data = $("#txtBusinessImage")[0].files; // for multiple files
for(var i = 0;i<file_data.length;i++){
fd.append("file"+[i], file_data[i]);
}
var other_data = $("#selectBusinessHiddenID").serializeArray();
$.each(other_data,function(key,input){
fd.append(input.name,input.value);
});
$.ajax({
url: '<?php echo site_url('Main_ctrl/upload_business_photo_do'); ?>',
data: fd,
enctype: 'multipart/form-data',
contentType: false,
processData: false,
type: 'POST', async : true,
success: function(data){
alert(data);
}
});
});
When im calling upload_business_photo_do() function via Ajax then it does't able to recive the name of image $_FILES['file']['name']
upload_business_photo_do()
{
$business_hidden_id=$this->input->post('selectBusinessHiddenID');
/*code for image*/
$config['upload_path']='./upload_101/';
$config['allowed_types']= 'jpg|png|jpeg';
$config['max_width'] = '6000';
$config['max_height'] = '4500';
$this->load->library('upload',$config);
for($i=0; $i<count($_FILES['file']['name']); $i++)
{
$_FILES['userfile']['name']= $_FILES['file']['name'][$i];
$_FILES['userfile']['type']= $_FILES['file']['type'][$i];
$_FILES['userfile']['tmp_name']= $_FILES['file']['tmp_name'][$i];
$_FILES['userfile']['error']= $_FILES['file']['error'][$i];
$_FILES['userfile']['size']= $_FILES['file']['size'][$i];
if(! $this->upload->do_upload())
{
/*----set flash message*/
echo "error";
}
else
{
echo "done";
}
}
}
try to use like this , its simple and easy
$("#uploadBusinessImg").on("click",function(e)
{
var formData = new FormData($("#form_name")[0]);
$.ajax({
url: '<?php echo site_url('Main_ctrl/upload_business_photo_do'); ?>',
processData: false,
contentType: false,
data: formData,
type: 'POST', async : true,
success: function(data){
alert(data);
}
});
});
and in controller use like this
if($_FILES['txtBusinessImageName'])
{
$file_ary = $this->reArrayFiles($_FILES['txtBusinessImageName']);
foreach ($file_ary as $file)
{
print 'File Name: ' . $file['name'];
print 'File Type: ' . $file['type'];
print 'File Size: ' . $file['size'];
}
}
and also use this function for convert files data into array for multiple images data
function reArrayFiles(&$file_post) {
$file_ary = array();
$file_count = count($file_post['name']);
$file_keys = array_keys($file_post);
for ($i=0; $i<$file_count; $i++) {
foreach ($file_keys as $key) {
$file_ary[$i][$key] = $file_post[$key][$i];
}
}
return $file_ary;
}
its working perfect , just try to use it . you don't need to add a extra codes of files with ajax.
use form tag and submit button for file upload.
<form method="post" enctype="multipart/form-data">
<input type="file" id="txtBusinessImage" class="form-control" name="txtBusinessImageName[]" multiple >
<input type="hidden" id="selectBusinessHiddenID" name="selectBusinessHiddenID" value="<?php echo $viewCompanyResult->company_id; ?>">
<input type="submit" id="uploadBusinessImg" value="Upload">
</form>
and remove enctype: 'multipart/form-data', from ajax call and try.
Change following for fetching files:
var file_data = $('#txtBusinessImage').prop('files')[0];
var fd = new FormData();
fd.append('file', file_data);

Ajax requests out of memory

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);
}

How to get an id in front of file for upload

First of all I'm very new to PHP and a bit better with Jquery. I managed to build an upload iFrame to upload images to a dropbox account for a webshop.
So somebody puts a T-shirt in the cart and then needs to upload some artwork. Customer clicks "upload" and is send to an iFrame which have the dropbox upload script. The url of the iFrame is something like this -> http://webshop.com/dropbox/index.html?id=10102013-88981
So far so good. The problem is however that when two people upload a file with the same name, the first file is being updated. So I need to have an unique id in front of the file. That unique id is the parameter at the end of the url.
So the question is how to get the id at the end of the url and how to place it in front of the uploaded image?
Ideal would be either a prefix for the file name or store everything in it's own folder.
I tried several things but my knowledge is limited, so any help greatly appreciated.
The upload script:
//Start the upload code.
........
......
if(sizeof($_FILES)===0){
echo "<li>No files were uploaded.</li>";
return;
}
foreach ($_FILES['ufiles']['name'] as $key => $value) {
if ($_FILES['ufiles']['error'][$key] !== UPLOAD_ERR_OK) {
echo $_FILES['ufiles']['name'][$key].' DID NOT upload.';
return;
}
$tmpDir = uniqid('/tmp/DropboxUploader-');
if (!mkdir($tmpDir)) {
echo 'Cannot create temporary directory!';
return;
}
$tmpFile = $tmpDir.'/'.str_replace("/\0", '_', $_FILES['ufiles']['name'][$key]);
if (!move_uploaded_file($_FILES['ufiles']['tmp_name'][$key], $tmpFile)) {
echo $_FILES['ufiles']['name'][$key].' - Cannot rename uploaded file!';
return;
}
try {
$uploader = new DropboxUploader($drop_account, $drop_pwd );
$uploader->upload($tmpFile, $drop_dir);
echo "<li>".$_FILES['ufiles']['name'][$key]."</li>" ;
// Clean up
if (isset($tmpFile) && file_exists($tmpFile))
unlink($tmpFile);
if (isset($tmpDir) && file_exists($tmpDir))
rmdir($tmpDir);
} catch(Exception $e) {
$error_msg = htmlspecialchars($e->getMessage());
if($error_msg === 'Login unsuccessful.' ) {
echo '<li style="font-weight:bold;color:#ff0000;">Unable to log into Dropbox</li>';
return;
}
if($error_msg === 'DropboxUploader requires the cURL extension.' ) {
echo '<li style="font-weight:bold;color:#ff0000;">Application error - contact admin.</li>';
return;
}
echo '<li>'.htmlspecialchars($e->getMessage()).'</li>';
}
}
UPDATE AS REQUESTED
The form:
<form class="formclass" id="ufileform" method="post" enctype="multipart/form-data">
<fieldset>
<div><span class="fileinput"><input type="file" name="ufiles" id="ufiles" size="32" multiple /></span>
</div>
</fieldset>
<button type="button" id="ubutton">Upload</button>
<button type="button" id="clear5" onclick="ClearUpload();">Delete</button>
<input type="hidden" name="id" id="prefix" value="" />
</form>
Upload.js (file is downloadable as free script on the internet):
(function () {
if (window.FormData) {
var thefiles = document.getElementById('ufiles'), upload = document.getElementById('ubutton');//, password = document.getElementById('pbutton');
formdata = new FormData();
thefiles.addEventListener("change", function (evt) {
var files = evt.target.files; // FileList object
var i = 0, len = this.files.length, file;
for ( ; i < len; i++ ) {
file = this.files[i];
if (isValidExt(file.name)) { //if the extension is NOT on the NOT Allowed list, add it and show it.
formdata.append('ufiles[]', file);
output.push('<li>', file.name, ' <span class="exsmall">',
bytesToSize(file.size, 2),
'</span></li>');
document.getElementById('listfiles').innerHTML = '<ul>' + output.join('') + '</ul>';
}
}
document.getElementById('filemsg').innerHTML = '';
document.getElementById('filemsgwrap').style.display = 'none';
document.getElementById('ubutton').style.display = 'inline-block';
document.getElementById('clear5').style.display = 'inline-block';
}, false);
upload.addEventListener('click', function (evt) { //monitors the "upload" button and posts the files when it is clicked
document.getElementById('progress').style.display = 'block'; //shows progress bar
document.getElementById('ufileform').style.display = 'none'; //hide file input form
document.getElementById('filemsg').innerHTML = ''; //resets the file message area
$.ajax({
url: 'upload.php',
type: 'POST',
data: formdata,
processData: false,
contentType: false,
success: function (results) {
document.getElementById('ufileform').style.display = 'block';
document.getElementById('progress').style.display = 'none';
document.getElementById('filemsgwrap').style.display = 'block';
document.getElementById('filemsg').innerHTML = '<ul>' + results + '</ul>';
document.getElementById('listfiles').innerHTML = '<ul><li>Select Files for Upload</ul>';
document.getElementById('ufiles').value = '';
document.getElementById('ubutton').style.display = 'none';
document.getElementById('clear5').style.display = 'none';
formdata = new FormData();
output.length = 0;
}
});
}, false);
} else {
// document.getElementById('passarea').style.display = 'none';
document.getElementById('NoMultiUploads').style.display = 'block';
document.getElementById('NoMultiUploads').innerHTML = '<div>Your browser does not support this application. Try the lastest version of one of these fine browsers</div><ul><li><img src="images/firefox-logo.png" alt="Mozilla Firefox" /></li><li><img src="images/google-chrome-logo.png" alt="Google Chrome Firefox" /></li><li><img src="images/apple-safari-logo.png" alt="Apple Safari" /></li><li><img src="images/maxthon-logo.png" alt="Maxthon" /></li></ul>';
}
document.getElementById('multiload').style.display = 'block';
document.getElementById('ufileform').style.display = 'block';
}());
function ClearUpload() { //clears the list of files in the 'Files to Upload' area and resets everything to be ready for new upload
formdata = new FormData();
output.length = 0;
document.getElementById('ufiles').value = '';
document.getElementById('listfiles').innerHTML = 'Select Files for Upload';
document.getElementById('ubutton').style.display = 'none';
document.getElementById('clear5').style.display = 'none';
document.getElementById('filemsgwrap').style.display = 'none';
}
function getExtension(filename) { //Gets the extension of a file name.
var parts = filename.split('.');
return parts[parts.length - 1];
}
function isValidExt(filename) { //Compare the extension to the list of extensions that are NOT allowed.
var ext = getExtension(filename);
for(var i=0; i<the_ext.length; i++) {
if(the_ext[i] == ext) {
return false;
break;
}
}
return true;
}
Change this line
$tmpFile = $tmpDir.'/'. $_POST['id'] . '-' . str_replace("/\0", '_', $_FILES['ufiles']['name'][$key]);
Note the $_POST['id'] which was added
EDIT: Changed to $_POST
Also in your form which you are posting add
<input type="hidden" name="id" value="<?=$_GET['id']; ?>" />
You could simply at time() to your file name.
http://php.net/manual/de/function.time.php
$tmpDir. '/' . time() . str_replace("/\0", '_', $_FILES['ufiles']['name'][$key]);

Categories