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
Related
What began here: PHP finding file where post INCLUDES portion of filename
I am trying to finish with this question.
Basically, now that I am able to post a variable to a PHP process, then use that process to find a file in a directory, I now need to be able to download the file if it exists.
Quick recap, after the user has entered a voyage number and the datatable has returned a list of voyages, the user then clicks the link, which is where I'll begin the code:
$('.voyageFileCall').on('click', function()
{
var voyage = $(this).attr('data-voyage');
$.post('fileDownload.php', {voyage:voyage}, function(data)
{
// here is where I need to where either display the file doesn't exist
// or the file downloads
});
});
The process 'fileDownload.php' looks like this:
<?php
if($_POST['voyage'] == true)
{
$voyage = $_POST['voyage'];
$files = scandir("backup/");
if(count($files) > 0)
{
$fileFound = false;
foreach($files as $file)
{
if((preg_match("/\b$voyage\b/", $file) === 1))
{
// I'm guessing the download process should happen here
echo "File found: $file \n"; // <-- this is what I currently have
$fileFound = true;
}
}
if(!$fileFound) die("File $voyage doesn't exist");
}
else
{
echo "No files in backup folder";
}
}
?>
I tried to use the answer found here: Download files from server php
But I'm not exactly sure where I should put the headers, or if I need to use them at all.
The quick solution which i can suggest you is: return path to file if it is exist, and return false if file doesn't exist.
After that in your JS code you can check, if your "data" == false, you can throw an error "file doesn't exist", and if it is not "false", you can call document.location.href = data; - it will redirect your browser to the file and it will be downloaded
Why don't you simply use download attribute:
<?php
if($_POST['voyage'] == true)
{
$voyage = $_POST['voyage'];
$files = scandir("backup/");
if(count($files) > 0)
{
$fileFound = false;
foreach($files as $file)
{
if((preg_match("/\b$voyage\b/", $file) === 1))
{
// I'm guessing the download process should happen here
echo 'File found: <a href="' . $file . '" download>' . $file . '</a> \n'; // <-- this is what I currently have
$fileFound = true;
}
}
if(!$fileFound) die("File $voyage doesn't exist");
}
else
{
echo "No files in backup folder";
}
}
?>
If you really want to use JavasScript to start download then use style="display:none;" for <a> and then in JS just click it:
echo 'File found: <a id="myDownload" style="display:none;" href="' . $file . '" download>' . $file . '</a> \n';
and call it:
$('.voyageFileCall').on('click', function()
{
var voyage = $(this).attr('data-voyage');
$.post('fileDownload.php', {voyage:voyage}, function(data)
{
if(document.getElementById("myDownload")){
document.getElementById("myDownload").click();
}else{
console.log("file does not exist");
}
});
});
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 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');
}
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);
?>
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";
}
?>