Ajax PHP upload script - php

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

Related

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

How to rename file in jquery file upload

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

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

upload media files, able to upload music and image files but not for video files

I'd like to upload all media files using ajax+php..
if I upload image and music file everything working as fine.
so I try upload video, it fails. what's wrong??
here is my ajax
function uploadFile() {
var file = document.getElementById("inputFile").files[0];
var quest_ID = document.getElementById("questionnaireID").value;
var quest_Number = document.getElementById("questNum").value;
var formdata = new FormData();
formdata.append("inputFile", file);
formdata.append("questionnaireID", quest_ID);
formdata.append("questionNumber", quest_Number);
formdata.append("media", 1);
if (xhr) {
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
var outMsg = xhr.responseText;
} else {
var outMsg = "There was a problem with the request. Error: " + xhr.status + " (" + xhr.statusText + ")"; //errror return
}
alert(outMsg);
}
};
xhr.open("POST", "addNew.php", false);
xhr.send(formdata);
}
return false;
}
And here is the php.
function getExtention($str){
return substr(strrchr($str,'.'),1);
}
if (isset($_POST["media"])){
$tmp_file = $_FILES['inputFile']['tmp_name'];
$target_file = $_POST["questionnaireID"] . "-" . $_POST["questionNumber"] . "." . getExtention(basename($_FILES['inputFile']['name']));
$upload_dir = "Assets/Media";
$path = $upload_dir."/".$target_file;
echo $path;
if(move_uploaded_file($tmp_file, $path)) {
$query = "insert into mediaDetails(available, mediaPath)";
$query .= " values(1, '{$path}')";
$result = execute($query);
if($result){
echo "Media added";
}
}else{
echo "cannot move file";
}
}
that code work when I upload images and music, but not video.
why I can't upload video file?
when I upload video file, it returns nothing, (no text at all)...
even echo $path is not shown....
any alternative way??
any answer appreciated, thank you.

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

Categories