how can I check if uploaded file using jQuery File Uploader filename already exists. I tried below code and it keeps overriding the first file uploaded. What I wanted is to prevent adding the file. Can someone guide me? Thanks.
Code:
$output_dir = "uploads/";
if(isset($_FILES["myfile"])) {
$ret = array();
// This is for custom errors;
// $custom_error= array();
// $custom_error['jquery-upload-file-error']="File already exists";
// echo json_encode($custom_error);
// die();
$error =$_FILES["myfile"]["error"];
//You need to handle both cases
//If Any browser does not support serializing of multiple files using FormData()
if(!is_array($_FILES["myfile"]["name"])) //single file
{
$fileName = $_FILES["myfile"]["name"];
// check if fileName already exists
if (file_exists($fileName)) {
$fileName = $_FILES["myfile"]["name"];
echo "string";
} else {
move_uploaded_file($_FILES["myfile"]["tmp_name"],$output_dir.$fileName);
$ret[]= $fileName;
}
}
else //Multiple files, file[]
{
$fileCount = count($_FILES["myfile"]["name"]);
for($i=0; $i < $fileCount; $i++)
{
$fileName = $_FILES["myfile"]["name"][$i];
move_uploaded_file($_FILES["myfile"]["tmp_name"][$i],$output_dir.$fileName);
$ret[]= $fileName;
}
}
echo json_encode($ret);
}
JS:
$(document).ready(function() {
var baseurl = window.location.protocol + "//" + window.location.host + "/rmc/";
var newurl = baseurl + 'document_items/upload';
var deleteurl = baseurl + 'document_items/delete';
$("#fileuploader").uploadFile({
url : newurl,
fileName : "myfile",
returnType : "json",
multiple : true, //allow multiple file upload
showFileSize : false, // show file size
acceptFiles : "image/*,application/pdf", // files accepted list
formData: {"name":"Ravi","age":31},
showAbort : true, // display abort button on upload
onSuccess:function(files,data,xhr) {
// $("#status").html("<font color='green'>Upload is success</font>");
},
afterUploadAll:function() {
swal({
title : "Success",
text : "File(s) successfuly uploaded.",
type : "success"
});
},
onError: function(files,status,errMsg)
{
swal({
title : "Error",
text : "Aw Snap! Something went wrong.",
type : "error"
});
},
deleteCallback: function (data, pd) {
for (var i = 0; i < data.length; i++) {
$.post(deleteurl, {op: "delete",name: data[i]},
function (resp,textStatus, jqXHR) {
// Show Message
swal("Success!", "File deleted successfuly!", "success");
});
}
pd.statusbar.hide(); // You choice.
}
});
});
Change your code as below and try again.
if(!is_array($_FILES["myfile"]["name"])) //single file
{
$fileName = $_FILES["myfile"]["name"];
// check if fileName already exists
if (file_exists($output_dir.$fileName)) {
$fileName = $_FILES["myfile"]["name"];
echo "string";
} else {
move_uploaded_file($_FILES["myfile"]["tmp_name"],$output_dir.$fileName);
$ret[]= $fileName;
}
}
Related
I am developing an application for sharing photos, I used ionic for the mobile part and the php for the backend part. But I have a problem when I upload a file that exceeds 2M.
Thank you very much for your good day.
This is my code:
//PHP backend : upload.php
<?php
header('Access-Control-Allow-Origin: *');
$target_path = "uploads/";
$target_path = $target_path . basename( $_FILES['file']['name']);
if(move_uploaded_file($_FILES['file']['tmp_name'], $target_path)) {
echo "Upload and move success";
} else{
echo $target_path;
echo "There was an error uploading the file, please try again!";
}
header ("Connection: close");
?>
// Ionic js
$scope.selectPicture = function(sourceType) {
var options = {
quality: 100,
destinationType: Camera.DestinationType.FILE_URI,
sourceType: sourceType,
saveToPhotoAlbum: false//,
//targetWidth: 800,
//targetHeight: 800
};
$cordovaCamera.getPicture(options).then(function(imagePath) {
// Grab the file name of the photo in the temporary directory
var currentName = imagePath.replace(/^.*[\\\/]/, '');
//Create a new name for the photo
var d = new Date(),
n = d.getTime(),
newFileName = n + ".jpg";
// If you are trying to load image from the gallery on Android we need special treatment!
if ($cordovaDevice.getPlatform() == 'Android' && sourceType === Camera.PictureSourceType.PHOTOLIBRARY) {
window.FilePath.resolveNativePath(imagePath, function(entry) {
window.resolveLocalFileSystemURL(entry, success, fail);
function fail(e) {
console.error('Error: ', e);
}
function success(fileEntry) {
var namePath = fileEntry.nativeURL.substr(0, fileEntry.nativeURL.lastIndexOf('/') + 1);
// Only copy because of access rights
$cordovaFile.copyFile(namePath, fileEntry.name, cordova.file.dataDirectory, newFileName).then(function(success){
$scope.image = newFileName;
}, function(error){
$scope.showAlert('Error', error.exception);
});
};
}
);
} else {
var namePath = imagePath.substr(0, imagePath.lastIndexOf('/') + 1);
// Move the file to permanent storage
$cordovaFile.moveFile(namePath, currentName, cordova.file.dataDirectory, newFileName).then(function(success){
$scope.image = newFileName;
}, function(error){
$scope.showAlert('Error', error.exception);
});
}
},
function(err){
// Not always an error, maybe cancel was pressed...
})
};
// Returns the local path inside the app for an image
$scope.pathForImage = function(image) {
if (image === null) {
return '';
} else {
return cordova.file.dataDirectory + image;
}
};
$scope.uploadImage = function() {
// Destination URL
var url = "http://myssite.com/upload.php";
// File for Upload
var targetPath = $scope.pathForImage($scope.image);
// File name only
var filename = $scope.image;;
var options = {
fileKey: "file",
fileName: filename,
chunkedMode: false,
mimeType: "multipart/form-data",
params : {'fileName': filename},
headers : { Connection: "close"}
};
$cordovaFileTransfer.upload(url, targetPath, options).then(function(result) {
console.log("SUCCESS: " + JSON.stringify(result.response));
}, function (err) {
console.log("ERROR: " + JSON.stringify(err));
}, function (progress) {
$timeout(function () {
$scope.downloadProgress = (progress.loaded / progress.total) * 100;
console.log("progress: " + progress + " dddd "+JSON.stringify(progress));
console.log("mytime "+$scope.downloadProgress);
$scope.progressval = $scope.downloadProgress;
});
});
My Config : upload max file size : 40M
post max size : 40M
this is my error : ERROR: {"code":3,"source":"file:///data/user/0/com.ionicframework.sample374926/files/1493805852934.jpg","target":"xxxxxx/… end of stream on Connection{xxxx.:80, proxy=DIRECT# hostAddress=xxxxxx cipherSuite=none protocol=http/1.1} (recycle count=0)"}
Hi i'm new to jquery. i'm trying to rename the file in upload..but i'm not able to do so
The Code i'm using for file upload
$(function() {
var btnUpload=$('#upload');
var status=$('#status');
new AjaxUpload(btnUpload, {
action: 'upload-file.php',
name: 'uploadfile',
onSubmit: function(finalname, ext){
if (! (ext && /^(pdf|doc|docx|xls|xlsx|text|)$/.test(ext))){
status.text('Only pdf, xls,doc,docs,xlsx and text files are allowed');
return false;
}
status.text('Uploading...');
},
onComplete: function(finalname, response){
status.text('');
if(response==="success"){
$('#head').val(finalname);
} else{
status.text('Upload Failed');
}
}
});
Php Code is
$uploaddir = 'uploads/files/';
$file = $uploaddir . basename($_FILES['uploadfile']['name']);
if (move_uploaded_file($_FILES['uploadfile']['tmp_name'], $file)) {
echo "success";
} else {
echo "error";
}
Html
<div id="upload" ><span>Browse<span></div><span id="status" ></span>
<input type="text" id="head" name="head" value="">
i am able to rename with php file...but not in jquery code it gives me wrong file name kindly help
I managed to rename the file name before upload...pepole down voted it inspite of helping. The changed i made to my code might be usefull for someone else
$(function() {
var btnUpload=$('#upload');
var status=$('#status');
var mm=Math.random().toString(36).substring(7) + new Date().getTime(); //to add new name of file
new AjaxUpload(btnUpload, {
action: 'upload-file.php?name='+mm, // gave a action to php file so i can use the same name
name: 'uploadfile',
onSubmit: function(file, ext){
if (! (ext && /^(pdf|doc|docx|xls|xlsx|text|)$/.test(ext))){
status.text('Only pdf, xls,doc,docs,xlsx and text files are allowed');
return false;
}
status.text('Uploading...');
},
onComplete: function(file, response){
var fileExtension = '.' + file.split('.').pop(); //got the file extestion
var outputfile = file.substr(0, file.lastIndexOf('.')) || file; //got the file name
var spaceremoved=outputfile.replace(/\s/g, '');//removed the space from file
var filename=mm+spaceremoved+fileExtension; //merged all to one
status.text('');
if(response==="success"){
$('#head').val(filename);
} else{
}
}
});
changes i made in php file
$uploaddir = 'uploads/files/';
if(isset($_GET['name'])){
$filena=$_GET['name'];
}
$basename=$filena.basename($_FILES['uploadfile']['name']);//merged the name
$finalna=preg_replace('/\s+/', '', $basename);//removed the space
$file = $uploaddir .$finalna;// merged to final
if (move_uploaded_file($_FILES['uploadfile']['tmp_name'], $file)) {
echo "success";
} else {
echo "error";
}
I need a CMS for make a Manga reader, so I bought PHP Manga: http://codecanyon.net/item/php-manga-manga-reader-website-solution/full_screen_preview/10102963
The problem is that manga images are not uploaded in order. For example, If I select and upload images (or pages) 1, 2, 3... He upload the images in 3,1,2 or so on.
Sadly they doesn't offer support anymore, and when I decided to buy it I didn't knew since I was unable to access to their forum without a license. So I need to fix this problem on my own.
This is the input form:
<?php echo Form::input('uploaderInput', R('uploaderInput'), array("type"=>"file", "data-href"=>URL('admin/base64'), "data-dir"=>"upload/manga/".$thisManga['slug']."/", "id"=>"inputUploader", "class"=>"form-control ", "multiple")) ?>
this is the template
$template->customJs .= '$("#chapterNumber").on("keyup", function(){
$("#chapterInfoDiv").show();
});
function readImage(input) {
for(var i=0,file; file = input.files[i]; i++) {
var FR = new FileReader();
FR.onload = function(e) {
var base64 = e.target.result,
h = $("#inputUploader").data("href"),
d = $("#inputUploader").data("dir")+$("#chapterNumber").val(),
options = {
type: "POST",
url: h,
data: { base64 : base64 , dir : d },
dataType: "json",
success: function(response) {
if(response.s == "ko"){
alert(response.m);
}else if(response.s == "ok"){
$("textarea#inputContent").val($("textarea#inputContent").val()+""+response.m+";");
}
}
};
$.ajax(options);
};
FR.readAsDataURL( input.files[i] );
}
}
$("#inputUploader").change(function(){
readImage( this );
});
';
This is the function
function secure_img_upload($file, $path, $options = array()){
// HANDLE OPTIONS
$validExtensions = isset($options['validExtensions']) ? $options['validExtensions'] : array('jpg', 'jpeg', 'png');
$surfix = isset($options['surfix']) ? $options['surfix'] : '';
// HANDLES FILES
$tempFile = $file['tmp_name'];
$fileName = $file['name'];
$extension = explode(".", $fileName);
$extension = strtolower(end($extension));
$imageName = sha1($fileName.uniqid());
$destination = rtrim($path, '/').'/'.$imageName.$surfix.'.'.$extension;
if(in_array($extension, $validExtensions)) {
$validExtension = true;
} else {
$validExtension = false;
}
// Run getImageSize function to check that we're really getting an image
if(getimagesize($tempFile) == false) {
$validImage = false;
} else {
$validImage = true;
}
if($validExtension == true && $validImage == true) {
if(move_uploaded_file($tempFile, $destination)) {
return $destination;
}else{
return array('s'=>'ko', 'm'=>T("Invalid path."));
}
}else{
return array('s'=>'ko', 'm'=>T("Invalid extension."));
}
Can you please help me to fix this problem? Really, I can't find anything wrong... The uploader is a single input with multi
there are a plugin to fix it
check it on codecanyon
That plugin will fix the order and showing the upload progress(speed,number of byte). The full detail can see on codecanyon
Hello I am trying to get to work this piece of code:
I am trying to build intelligent images uploader, that will care about the html 5 multiple selection bug (or feature as someone can say) which will delete "previous files" when I decide to select few extra. Also it has some primitive approach to permit user selecting file that was selected previously.
This part works fine, I am seeing images previews and also echoing "file" into console corresponds to number of files.
What is strange is return (echo) from PHP script which says that file is in /tmp directory and also size is correct, but file don't get moved.
I checked permissions and set uploaded folder to "lucky" 777.
I checked /tmp folder and file is no there but PHP script is saying taht is here.
I know about that you can't set , it is logical why you can't, but should echo from PHP script shows size and tmp location of this file then if this is a issue ?
code here:
var noveSub = [];
var noveSubMeno = [];
var noveSubVelkost = [];
function samotnyUpload() {
var fd = new FormData();
fd.append('upload', noveSub[0]);
// trying just first file for testing
$.ajax({
url: '/upload/upload.php',
data: fd,
cache: false,
processData: false,
contentType: false,
type: 'POST',
success: function(data){
console.log(data);
}
});
}
function pridatSubory() {
$("li.pridaj").click(function() {
$("input").trigger("click");
});
function pushniNovy(subor) {
noveSub.push(subor);
noveSubMeno.push(subor.name);
noveSubVelkost.push(subor.size);
previewNovy(subor);
}
function previewNovy(subor) {
var li = document.createElement("li");
var img = document.createElement("img");
img.file = subor;
li.appendChild(img);
$(li).insertBefore("li.pridaj");
var reader = new FileReader();
reader.onload = (function(aImg) { return function(e) { aImg.src = e.target.result; }; })(img);
reader.readAsDataURL(subor);
}
var inputElement = document.getElementById("vyberSubor");
inputElement.addEventListener("change", handleFiles, false);
function handleFiles() {
var sub = this.files;
for (i=0; i<sub.length; i++) {
pos = noveSubMeno.indexOf(sub[i].name);
if (pos !== -1) {
if (noveSubVelkost[pos] !== sub[i].size) {
pushniNovy(sub[i]);
}
} else {
pushniNovy(sub[i]);
}
}
}
PHP FILE :
<?php
if ($_FILES["upload"]["error"] > 0)
{
echo "Error: " . $_FILES["upload"]["error"] . "<br>";
}
else
{
echo "Upload: " . $_FILES["upload"]["name"] . "<br>";
echo "Type: " . $_FILES["upload"]["type"] . "<br>";
echo "Size: " . ($_FILES["upload"]["size"] / 1024) . " kB<br>";
echo "Stored in: " . $_FILES["upload"]["tmp_name"];
echo "<br><br>";
echo move_uploaded_file($_FILES["upload"]["tmp_name"], "upload/".$_FILES["file"]["name"]);
}
?>
OUTPUT FROM PHP FILE in console:
Upload: erb128.png<br>Type: image/png<br>Size: 4.734375 kB<br>Stored in: /tmp/phpdTy053<br><br>
It may actually be a syntax problem. You're mixing strings and variables in your move_uploaded_file call. Try this instead:
$destination = "upload/".$_FILES["file"]["name"];
$result = move_uploaded_file($_FILES["upload"]["tmp_name"], $destination);
echo $result;
I rethink this approach. to use PUT for upload. I have read that some benefits are:
small memory footprint even if You are uploading very big files
and also saw scripts that are able to pause upload.
changes to code (only draft):
var xhr = new XMLHttpRequest();
function samotnyUpload() {
xhr.open("put", "http://pingpong.local/upload/upload.php", true);
xhr.setRequestHeader("X-File-Name", noveSubMeno[0]);
xhr.setRequestHeader("X-File-Size", noveSubVelkost[0]);
xhr.send(noveSub[0]);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
console.log(xhr.responseText);
}
};
}
and PHP script:
<?php
$filename = $_SERVER['HTTP_X_FILE_NAME'];
echo $filename;
$filesize = $_SERVER['HTTP_X_FILE_SIZE'];
echo $filesize;
$in = fopen('php://input','r');
$tmp = fopen('tempfile.ext','w');
while($data = fread($in, 1024)) fwrite($tmp, $data);
fclose($in);
fclose($tmp);
?>
I'm using Valum's Ajax-Uploader script to upload files to my server. Because there's a good chance of the uploaded files have the same name I add a random number to the filename. The problem is that the ajax uploader is returning the original filename into the input[type=text] instead of the new filename with the random number added. I've tried echo $file; instead of echo "success"; , but all that happens is that the file is uploaded, and the script returns with the pop-up error.
jQuery(function() {
var url = "http://example.com/uploads/samples/";
var button = jQuery('#up');
new AjaxUpload(button, {
action: 'upload.php',
name: 'upload',
autoSubmit: true,
onSubmit: function(file, ext) {
// do stuff while file is uploading
},
onComplete: function(file, response) {
if (response === "success") {
$('input[type=text]').val(url + file);
} else {
jAlert('Something went wrong!', 'Error!');
}
}
});
});
upload.php
<?php
$uploaddir = '/path/to/uploaddir/';
$file = basename($_FILES['file']['name']);
if($_FILES['file']['name']) {
$file = preg_replace('/\s+/', '_', $file);
$rand = rand(0000,9999);
if (move_uploaded_file($_FILES['file']['tmp_name'], $uploaddir . $rand . $file)) {
echo "success";
} else {
echo "error";
}
}
?>
Change
$('input[type=text]').text(url + file);
To
$('input[type=text]').val(url + file);
Client code and server code exist completely independently of each other. Basically, your JavaScript code has no way of knowing what your PHP code just did. url doesn't update automatically when you change it in the PHP file.
An alternate solution would be to have your PHP code echo the new filename, or echo an error message.
For example:
PHP
<?php
if (move_uploaded_file($_FILES['file']['tmp_name'], $uploaddir . $rand . $file)) {
// Everything went well! Echo the dollar sign ($) plus the new file name
echo '$' . $_FILES['file']['tmp_name'], $uploaddir . $rand . $file;
} else {
echo "error";
}
?>
JS
onComplete: function(file, response) {
// If the first character of the response is the "$" sign
if (response.substring(0,1) == "$") {
$('input[type=text]').val(response.substring(1));
} else {
jAlert('Something went wrong!', 'Error!');
}
}
I would like to suggest using date and time to create a unique random number.
You can use following function in your code, I am fully trusted on this function because I already use this in my project.
`
/**
* This function return unique string as a key
*/
public static function getUniqueKey(){
$currentDateTime = date("YmdHisu");
return $currentDateTime . BTITTools::createRandomString(3);
}
`
# My Code Programs