How to rename file in jquery file upload - php

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

Related

ionic cordovaFileTransfer with api php code error 3

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.s‌​ample374926/files/14‌​93805852934.jpg","ta‌​rget":"xxxxxx/… end of stream on Connection{xxxx.:80, proxy=DIRECT# hostAddress=xxxxxx cipherSuite=none protocol=http/1.1} (recycle count=0)"}

Check whether the file already exists in jquery

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

PHP not echoing after file upload completed

I have some simple code to upload file using drop zone. It's uploading the file just fine but for some reason it doesn't echo "done uploading" at the end of the code.
Am I missing something obvious here?
<script type="text/javascript">
Dropzone.options.myDropzone = {
addRemoveLinks: true,
removedfile: function(file) {
var _ref;
return (_ref = file.previewElement) != null ? _ref.parentNode.removeChild(file.previewElement) : void 0;
}
};
</script>
<div id="dropzone">
<form id="myDropzone" action="#" class="dropzone" id="demo-upload">
<div class="dz-message">
Drop files here or click to upload.<br />
</div>
</form>
</div>
<?php
$ds = DIRECTORY_SEPARATOR; //1
$storeFolder = 'uploads'; //2
if (!empty($_FILES)) {
$tempFile = $_FILES['file']['tmp_name']; //3
$targetPath = dirname( __FILE__ ) . $ds. $storeFolder . $ds; //4
$targetFile = $targetPath. $_FILES['file']['name']; //5
move_uploaded_file($tempFile,$targetFile); //6
echo "done uploading";
}
?>
Try this:
if(move_uploaded_file($tempFile,$targetFile)) {
echo "done uploading";
} else {
echo 'error!';
}
You can activate error_reporting to see the error from move_uploaded_file
Edit: Ugly hack, just for testing. DO NOT USE THIS IN PRODUCTION!!!
if(move_uploaded_file($tempFile,$targetFile)) {
$_SESSION["success"] = "upload done";
echo $_SESSION["success];
} else {
echo 'error!';
}
Since Dropzone uses AJAX to post requests to server you will not see the response line ordinary PHP response when you echo something.
Try in this way
<script type="text/javascript">
Dropzone.options.myDropzone = {
...
success: function(file, response){
alert(response); // Just to test, you can remove this
// Do what you want
// Like:
if(response == "success") {
// Uploaded ok
} else {
// Failed to upload
}
}
};
</script>
In this way after successful AJAX request you can catch the response and do whatever you want.
Ofcoruse, like #tftd said, You need to wrap move_uploaded_file like:
if(move_uploaded_file(...)) {
// done uploading
echo json_encode('success');
} else {
// failed moving
echo json_encode('error');
}

Adding Random Number to Uploaded File

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

Ajax PHP upload script

Where do i put my PHP SQL query, to insert image information to my database?
I tried just before the echo "success"; however it had no effect.
<!-- Upload Button-->
<div id="upload" >Upload File</div><span id="status" ></span>
<!--List Files-->
<ul id="files" ></ul>
PHP handling
<?php
$uploaddir = './uploads/';
$file = $uploaddir . basename($_FILES['uploadfile']['name']);
if (move_uploaded_file($_FILES['uploadfile']['tmp_name'], $file)) {
echo "success";
} else {
echo "error";
}
?>
Javascript section
$(function () {
var btnUpload = $('#upload');
var status = $('#status');
new AjaxUpload(btnUpload, {
action: 'upload-file.php',
//Name of the file input box
name: 'uploadfile',
onSubmit: function (file, ext) {
if (!(ext && /^(jpg|png|jpeg|gif)$/.test(ext))) {
// check for valid file extension
status.text('Only JPG, PNG or GIF files are allowed');
return false;
}
status.text('Uploading...');
},
onComplete: function (file, response) {
//On completion clear the status
status.text('');
//Add uploaded file to list
if (response === "success") {
$('<li></li>').appendTo('#files').html('<img src="./uploads/' + file + '" alt="" /><br />' + file).addClass('success');
} else {
$('<li></li>').appendTo('#files').text(file).addClass('error');
}
}
});
});
The query should be right before success echo, so you have to verify what is returning to you the move_uploaded_file method.
Verify if ./upload/ is the right path and if you have read/write access (0777) on this directory.
Also make sure that you're connected to database:
<?php
$conn = mysql_connect("HOST","USER","PASSWORD");
$db = mysql_select_db("DB_NAME");
$uploaddir = './uploads/';
$file = $uploaddir . basename($_FILES['uploadfile']['name']);
if (move_uploaded_file($_FILES['uploadfile']['tmp_name'], $file)) {
mysql_query("INSERT INTO photos VALUES ('your_values')");
echo "success";
} else {
echo "error";
}
?>

Categories