Dropzone file upload new name? - php

Here is what my user interface looks like:
Here is my code. I want to change the file name when the file is uploaded.
index.html
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
<title>LCW DOSYA UPLOAD V1.0</title>
<link rel="stylesheet" href="dropzone.css"/>
<script src="dropzone.js"></script>
</head>
<body>
<center>
<label for="belge">Belge No:</label><br><br>
<input type="text" id="belge" name="belge"><br>
<br>
<input type="radio" id="ups" name="gender" value="ups">
<label for="ups">UPS</label><br>
<input type="radio" id="fillo" name="gender" value="fillo">
<label for="fillo">Fillo</label><br></center><br><br>
<form action="upload.php" class="dropzone" id="my-awesome-dropzone">
</form>
<script type="text/javascript">
Dropzone.options.myAwesomeDropzone = {
paramName: "file", // The name that will be used to transfer the file
maxFilesize: 20000, // MB
renameFile: function (file) {
let newName = new Date().getTime() + '_' + file.name;
return newName;}
};
</script>
</body>
</html>
upload.php
<?php
$dizin="images/";
$kaynak=$_FILES["file"]["tmp_name"];
$hedef=$dizin.$_FILES["file"]["name"];
if(move_uploaded_file($kaynak,$hedef)==true){
echo 'Yukleme Basarili';
}else {
echo 'HATA';
}
?>
The file name should be: belge + radio + 'filename.jpg'
What should I to make it should happen when I upload files?

<script type="text/javascript">
Dropzone.options.myAwesomeDropzone = {
paramName: "file", // The name that will be used to transfer the file
maxFilesize: 20000, // MB
renameFile: function (file){
var belge = document.getElementById('belge').value;
var radios = document.getElementsByName('gender');
for(var i = 0, length = radios.length; i < length; i++){
if(radios[i].checked){
var radio = radios[i].value;
}
}
let newName = belge + '_' + radio + '_' + file.name;
return newName;
}
};
</script>

Related

Dropzone integration into form

I am running into the issue where the form input fields are not passing data along with the files when I try to integrate dropzone into my form. I need it to pass the additional fields as it contains info for the file name for the files. Here is what I have, if someone could please tell me what I am doing wrong. I have removed some folder/file names for security, I italiced those
Form Page:
<form action="upload_photos.php" method="post" enctype="multipart/form-data">
<div class="form_quartercontent">
<select name="fp_id" id="fp_id">
<option value="*some option*" >*Option Label*</option>
</select>
</div>
<div class="form_quartercontent">
<input name="order_id" type="hidden" id="order_id" value="the order id #" />
</div>
<div class="clear"></div>
<div class="dropzone" id="myDropzone"></div>
<div class="form_quartercontent"><input name="submit-all" type="submit" class="form-submit-button" id="submit-all" value="Upload Photo" /></div></form>
<script>Dropzone.options.myDropzone= {
url: 'upload_photos.php',
autoProcessQueue: false,
uploadMultiple: true,
parallelUploads: 100,
maxFiles: 100,
maxFilesize: 3,
acceptedFiles: 'image/*',
addRemoveLinks: true,
init: function() {
var dzClosure = this; // Makes sure that 'this' is understood inside the functions below.
// for Dropzone to process the queue (instead of default form behavior):
document.getElementById("submit-all").addEventListener("click", function(e) {
// Make sure that the form isn't actually being sent.
e.preventDefault();
e.stopPropagation();
dzClosure.processQueue();
});
//send all the form data along with the files:
this.on("sending", function(file, xhr, formData) {
//formData.append('task_name', jQuery('#task_name').val());
$("form").find("input").each(function(){
formData.append($(this).attr("name"), $(this).val());
});
});
}
}
</script>
**
Upload PHP:**
$order_photo = $_POST['order_id'];
$photo_fp = $_POST['fp_id'];
if(!empty($_FILES)){
// Include the database configuration file
require("includes/*databaseconnection.php*");
if(!($p_update = mysqli_query($link,"INSERT INTO *table* SET order_id='$order_photo',fp_id='$photo_fp'"))){
printf("%s", sprintf("internal error %d:%s\n", mysqli_errno(), mysqli_error()));
exit();
}
$photo_id = mysqli_insert_id($link);
$extension = strrchr($_FILES['file']['name'],'.');
$extension = strtolower($extension);
$save_path = '*pathtofolder*/'. $order_photo .'/*storingfolder*/';
if(!is_dir($save_path)) mkdir($save_path);
$filename = $save_path . $order_photo ."_". $photo_fp."_". $photo_id . $extension;
move_uploaded_file($_FILES['file']['tmp_name'],$filename);
}
This is my working solution:
Form Page:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>upload Files</title>
<script src="https://code.jquery.com/jquery-3.6.3.min.js"></script>
<script src="https://unpkg.com/dropzone#5/dist/min/dropzone.min.js"></script>
<link
rel="stylesheet"
href="https://unpkg.com/dropzone#5/dist/min/dropzone.min.css"
type="text/css"
/>
</head>
<body>
<form action="upload_photos.php" method="post" enctype="multipart/form-data">
<div class="form_quartercontent">
<select id="fp_id" name="fp_id">
<option value="200">200</option>
<option value="300">300</option>
</select>
</div>
<div class="form_quartercontent">
<input name="order_id" type="hidden" id="order_id" value="1" />
</div>
<div class="clear"></div>
<div class="dropzone" id="myDropzone"></div>
<div class="form_quartercontent">
<input name="submit-all" type="submit" class="form-submit-button" id="submit-all" value="Upload Photo" />
</div>
</form>
<script>Dropzone.options.myDropzone= {
url: 'upload_photos.php',
autoProcessQueue: false,
uploadMultiple: true,
parallelUploads: 100,
maxFiles: 100,
maxFilesize: 3,
acceptedFiles: 'image/*',
addRemoveLinks: true,
init: function() {
var dzClosure = this;
document.getElementById("submit-all").addEventListener("click", function(e) {
e.preventDefault();
e.stopPropagation();
dzClosure.processQueue();
});
this.on("sending", function(file, xhr, formData) {
$("form").find("input").each(function(){
formData.append($(this).attr("name"), $(this).val());
});
$("form").find("select").each(function(){
formData.append($(this).attr("name"), $(this).val());
});
});
this.on("success", function(file, serverFileName) {
var sfn = serverFileName
this.on("removedfile", function(file) {
$.post("deleteFiles.php", { "file_name" : sfn },function(data){
alert('File has been successfully deleted')
});
});
});
}
}
</script>
</body>
</html>
upload_photos.php:
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli('database_server', 'username', 'password', 'database_name');
if($_FILES['file'] && $_POST['submit-all']){
$order_photo = $_POST['order_id'];
$photo_fp = $_POST['fp_id'];
$stmt = $mysqli->prepare("INSERT INTO files(order_id, fp_id) VALUES (?, ?)");
$stmt->bind_param("ss", $order_photo, $photo_fp);
$stmt->execute();
$photo_id = $stmt->insert_id;
$save_path = sprintf("files/%s/sortingFolder/", $order_photo);
if(!is_dir($save_path))
{
mkdir('files');
mkdir(sprintf("files/%s",$order_photo));
mkdir(sprintf("files/%s/sortingFolder",$order_photo));
}
$count = count($_FILES['file']['name']);
for($i=0; $i < $count; $i++ )
{
$fileName[] = mb_strtolower(basename($_FILES['file']['name'][$i]),'UTF-8');
$extension[] = pathinfo($fileName[$i], PATHINFO_EXTENSION);
$makeHash[] = hash('sha1',date('YmdHis').mt_rand(100,999));
$fileNewName[] = sprintf($save_path . $order_photo . "_" . "%s" . "_". $photo_id ."_". $makeHash[$i] . "." . $extension[$i],$photo_fp);
move_uploaded_file($_FILES['file']['tmp_name'][$i],$fileNewName[$i]);
print $fileNewName[$i];
}
}
?>
deleteFiles.php:
<?php
header("Content-Type: application/json; charset=UTF-8");
$data['fileName'] = $_POST['file_name'];
unlink($data['fileName']);
print json_encode($data);
?>
my database structure:
You could have also used the formData.append("variableName", "valueOfVariable") and in your *.php file just read the $_POST['variableName']. This way you can get rid of $("form").find("input") functions.

How to upload multiple images to a folder using ajax php and jquery

I am trying to upload multiple images to a folder at a time by using AJAX, JQuery, and PHP. The code is running for single file upload but not running for multiple image upload.
If I am uploading a single image without loop then its working fine but in case of loop it's not working.
I am using the following code.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Upload Iamge</title>
<link href="style.css" rel="stylesheet" type="text/css">
<script src="jquery-1.12.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#but_upload").click(function(){
var fd = new FormData();
//following code is working fine in for single image upload
// var files = $('#file')[0].files[0];
// fd.append('file',files);
//this code not working for multiple image upload
var names = [];
for (var i = 0; i < $('#file').get(0).files.length; ++i) {
names.push($('#file').get(0).files[i].name);
}
fd.append('file[]',names);
/*var ins = document.getElementById('file').files.length;
for (var x = 0; x <ins; x++) {
fd.append("file", document.getElementById('file').files[x]);
}*/
$.ajax({
url:'upload.php',
type:'post',
data:fd,
contentType: false,
processData: false,
success:function(response){
if(response != 0){
$("#img").attr("src",response);
}
},
error:function(response){
alert('error : ' + JSON.stringify(response));
}
});
});
});
</script>
</head>
//HTML Part
<body>
<div class="container">
<h1>AJAX File upload</h1>
<form method="post" action="" id="myform">
<div>
<img src="" id="img" width="100" height="100">
</div>
<div>
<input type="file" id="file" name="file" multiple="multiple" />
<input type="button" class="button" value="Upload"
id="but_upload">
</div>
</form>
</div>
</body>
</html>
//PHP Code
<?php
/* Getting file name */
echo "<script>alert('yes');</script>";
//without loop working fine
$count = count($_FILES['file']['name']);
for ($i = 0; $i < $count; $i++) {
$filename = $_FILES['file']['name'][$i];
/* Location */
$location = "upload/".$filename;
/* Upload file */
if(move_uploaded_file($_FILES['file']['tmp_name'],$location)){
echo $location;
} else {
echo 0;
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Upload Iamge</title>
<script type="text/javascript">
$(document).ready(function(){
$("#but_upload").click(function(){
var fd = new FormData();
//following code is working fine in for single image upload
// var files = $('#file')[0].files[0];
// fd.append('file',files);
//this code not working for multiple image upload
var names = [];
var file_data = $('input[type="file"]')[0].files;
// for multiple files
for(var i = 0;i<file_data.length;i++){
fd.append("file_"+i, file_data[i]);
}
fd.append('file[]',names);
/*var ins = document.getElementById('file').files.length;
for (var x = 0; x <ins; x++) {
fd.append("file", document.getElementById('file').files[x]);
}*/
$.ajax({
url:'upload.php',
type:'post',
data:fd,
contentType: false,
processData: false,
success:function(response){
if(response != 0){
$("#img").attr("src",response);
}
},
error:function(response){
alert('error : ' + JSON.stringify(response));
}
});
});
});
</script>
</head>
//HTML Part
<body>
<div class="container">
<h1>AJAX File upload</h1>
<form method="post" action="" id="myform">
<div>
<img src="" id="img" width="100" height="100">
</div>
<div>
<input type="file" id="file" name="file" multiple="multiple" />
<input type="button" class="button" value="Upload"
id="but_upload">
</div>
</form>
</div>
</body>
</html>
have made changes in below code
var file_data = $('input[type="file"]')[0].files; // for multiple files
for(var i = 0;i<file_data.length;i++){
fd.append("file_"+i, file_data[i]);
}
fd.append('file[]',names);
And there are also changes in PHP code
<?php
/* Getting file name */
//without loop working fine
$count = count($_FILES);
for ($i = 0; $i < $count; $i++) {
$filename = $_FILES['file_'.$i];
/* Location */
echo $location = "upload/".$filename['name'];
/* Upload file */
if(move_uploaded_file($filename['tmp_name'],$location)){
echo $location;
} else {
echo 0;
}
}
?>
count of files and file name are comming in a different way so I have made the changes as required instead of if gives file array like $_FILE['file_0'],$_FILE['file_1'] and so on, I have also change the permission of upload directory please check if your directory have read and write permission (777) or not, this code works for me you can try I hope it will work for you also :-)
In the loop you will need to add index of particular file
move_uploaded_file($_FILES['file']['tmp_name'][$i],$location); // $i is index

Upload Multiple Files with PHP and JQuery

I have been trying my hands on PHP lately, so far so good until I hit a brick wall. Here's a little piece of code that I have. It's allowing me to upload a single file, but what I want is to be able to upload multiple files.
Here's the PHP and HTML files:
<html>
<head>
<meta charset="utf-8" />
<title>Ajax upload form</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
function sendfile(){
var fd = new FormData();
for (var i = 0, len = document.getElementById('myfile').files.length; i < len; i++) {
fd.append("myfile", document.getElementById('myfile').files[i]);
}
$.ajax({
url: 'uploadfile.php',
data: fd,
processData: false,
contentType: false,
type: 'POST',
success: function(data){
alert(data);
}
});
}
</script>
</head>
<body>
<form action="uploadfile.php" method="post" enctype="multipart/form-data" id="form-id">
<p><input id="myfile" type="file" name="myfile" multiple=multiple/>
<input type="button" name="upload" id="upload" value="Upload" onclick="sendfile()" id="upload-button-id" /></p>
</form>
</body>
</html>
And the PHP file:
<?php
$target = "uploadfolder/";
//for($i=0; $i <count($_FILES['myfile']['name']); $i++){
if(move_uploaded_file($_FILES['myfile']['tmp_name'], $target.$_FILES['myfile']['name'])) {
echo 'Successfully copied';
}else{
echo 'Sorry, could not copy';
}
}//
?>
Any help would be highly appreciated.
Index.html
<html>
<head>
<title>Load files</title>
<script src="jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#myfiles').on("change", function() {
var myfiles = document.getElementById("myfiles");
var files = myfiles.files;
var data = new FormData();
for (i = 0; i < files.length; i++) {
data.append('file' + i, files[i]);
}
$.ajax({
url: 'load.php',
type: 'POST',
contentType: false,
data: data,
processData: false,
cache: false
}).done(function(msg) {
$("#loadedfiles").append(msg);
});
});
});
</script>
</head>
<body>
<div id="upload">
<div class="fileContainer">
<input id="myfiles" type="file" name="myfiles[]" multiple="multiple" />
</div>
</div>
<div id="loadedfiles">
</div>
</body>
</html>
load.php
<?php
$path="myfiles/";//server path
foreach ($_FILES as $key) {
if($key['error'] == UPLOAD_ERR_OK ){
$name = $key['name'];
$temp = $key['tmp_name'];
$size= ($key['size'] / 1000)."Kb";
move_uploaded_file($temp, $path . $name);
echo "
<div>
<h12><strong>File Name: $name</strong></h2><br />
<h12><strong>Size: $size</strong></h2><br />
<hr>
</div>
";
}else{
echo $key['error'];
}
}
?>

PHP & AJAX Upload File Fails Some times

I am creating a simple video uploader for an adults site and it works for small files but it doesn't for bigger files. I have not tested what the break line is but I know for sure it works for 5mb or so file and fails for 100mb+ files. In the server I have set the maximum upload size and maximum post size to 1000mb in the php5.ini. Can you spot anything wrong with the code or do you think this is a server problem? The site is being hosted in a linux godaddy server. Here is a link for testing:
http://munchmacouchi.com/upload_sample/upload.php
Here is the code in upload.js:
var handleUpload = function(event){
event.preventDefault();
event.stopPropagation();
var fileInput = document.getElementById('file');
var data = new FormData();
data.append('ajax',true);
for ( var i = 0 ; i < fileInput.files.length ; i++ ){
data.append('file[]',fileInput.files[i]);
}
var request = new XMLHttpRequest();
request.upload.addEventListener('progress', function(event){
if(event.lengthComputable){
var percent = event.loaded / event.total ;
var progress = document.getElementById('upload_progress');
while(progress.hasChildNodes())
progress.removeChild(progress.firstChild);
progress.appendChild(document.createTextNode(Math.round(percent*100)+' %'));
}
});
request.upload.addEventListener('load', function(event){
document.getElementById('upload_progress').style.display='none';
});
request.upload.addEventListener('error', function(event){
alert('Upload Failed');
});
request.addEventListener('readystatechange', function(event){
if(this.readyState == 4){
if(this.status == 200){
var links = document.getElementById('uploaded');
var uploaded = eval(this.response);
var div, a;
for(var i = 0 ; i < uploaded.length ; i++){
div = document.createElement('div');
a = document.createElement('a');
a.setAttribute('href','files/'+uploaded[i]);
a.appendChild(document.createTextNode(uploaded[i]));
div.appendChild(a);
links.appendChild(div);
}
}else{
console.log("Server replied with HTTP status " + this.status);
}
}
});
request.open('POST','upload.php');
request.setRequestHeader('Cache-Control', 'no-cache');
document.getElementById('upload_progress').style.display='block';
request.send(data);
}
window.addEventListener('load',function(event){
var submit = document.getElementById('submit');
submit.addEventListener('click',handleUpload);
});
and for upload.php:
<?php
if(!empty($_FILES['file'])){
foreach($_FILES['file']['name'] as $key => $name){
if($_FILES['file']['error'][$key] == 0 && move_uploaded_file($_FILES['file']['tmp_name'][$key], "files/{$name}")){
$uploaded[] = $name;
}
}
if(!empty($_POST['ajax'])){
die(json_encode($uploaded));
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Upload Test</title>
<h3>Upload Test</h3>
<script type="text/javascript" src="upload.js"></script>
<style type="text/css">
#upload_progress {display:none;}
</style>
</head>
<body>
<div id="uploaded">
<?php
if(!empty($uploaded)){
foreach($uploaded as $name){
echo '<div>', $name , '</div>';
}
}
?>
</div>
<div id="upload_progress"></div>
<div>
<form action="" method="post" enctype="multipart/form-data">
<div>
<input type="file" id="file" name="file[]" multiple="multiple"/>
<input type="submit" id="submit" value="Upload"/>
</div>
</form>
</div>
</body>
</html>

How to detect the number of uploaded files and their names before uploading from client side by javascript or jquery?

I want to upload multiple files and have a file called test.php with this code:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<script src="js/jquery-1.8.0.min.js"></script>
<script>
$(function(){
var myVar;
$('form').submit(function(){
myVar = setInterval(ajax, 1000);
});
var ajax = function() {
$.ajax({
url: 'test2.php',
type: 'post',
success: function(ajax_result){
$('.result').html(ajax_result);
if (!ajax_result) {
clearInterval(myVar);
}
},
error: function(){
alert('error');
}
});
};
});
</script>
</head>
<body style="width:100%; height:100%;">
<form action="test2.php" target="iframe" method="post" enctype="multipart/form-data" >
<input type="hidden" name="<?php echo ini_get("session.upload_progress.name"); ?>" value="fil" />
<input name="file[]" type="file" multiple />
<input type="submit">
</form>
<iframe id="iframe" name="iframe"></iframe>
<div class="result" style="width:100%; height:100%;"></div>
</body>
</html>
and a file called test2.php with this code:
<?php
session_start();
if (isset($_FILES['file'])){
for ($i = 0; $i < count($_FILES['file']['tmp_name']); $i++) {
move_uploaded_file($_FILES['file']['tmp_name'][$i],'a/'.$_FILES['file']['name'][$i]);
}
}
if (isset($_SESSION[$key = ini_get("session.upload_progress.prefix") . 'fil'])) {
var_dump($_SESSION[$key]);
} else echo false;
?>
Now I want before sending files to server to detect the number of files selected via their names in the client side.
How can I do this?
$('form').submit(function() {
var numberOfFilesAboutToBeSubmitted = $("[name='file[]']", this ).prop("files").length;
});
Note that you are not submitting any files with your ajax request, it has no association with your form at all.
Also note that this doesn't work in IE < 10

Categories