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.
Related
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>
I am using croppie plugin for crop the image which is working perfectly. The image was stored in my folder and the image size is showing zero bytes.It is working perfectly on localhost but not working on the server. Would you help me in this?
<form action="process.php" id="form" method="post">
<div id="upload-demo"></div>
<input type="hidden" id="imagebase64" name="imagebase64">
<input type="submit" name="submit" value="save" class="upload-result">
</form>
if(isset($_POST['submit'])){
$data = $_POST['imagebase64'];
list($type, $data) = explode(';', $data);
list(, $data) = explode(',', $data);
$data = base64_decode($data);
$imageName = time().'.png';
file_put_contents('images/profile/'.$imageName, $data);
// echo $imageName;
}
This is working file. This may help you.
<?php
if(isset($_POST['imagebase64'])){
$data = $_POST['imagebase64'];
list($type, $data) = explode(';', $data);
list(, $data) = explode(',', $data);
$data = base64_decode($data);
file_put_contents('image64.png', $data);
}
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="utf-8">
<title>Test</title>
<link href="croppie.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="croppie.js"></script>
<script type="text/javascript">
$( document ).ready(function() {
var $uploadCrop;
function readFile(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$uploadCrop.croppie('bind', {
url: e.target.result
});
$('.upload-demo').addClass('ready');
}
reader.readAsDataURL(input.files[0]);
}
}
$uploadCrop = $('#upload-demo').croppie({
viewport: {
width: 200,
height: 200,
type: 'circle'
},
boundary: {
width: 300,
height: 300
}
});
$('#upload').on('change', function () { readFile(this); });
$('.upload-result').on('click', function (ev) {
$uploadCrop.croppie('result', {
type: 'canvas',
size: 'original'
}).then(function (resp) {
$('#imagebase64').val(resp);
$('#form').submit();
});
});
});
</script>
</head>
<body>
<form action="process.php" id="form" method="post">
<input type="file" id="upload" value="Choose a file">
<div id="upload-demo"></div>
<input type="hidden" id="imagebase64" name="imagebase64">
Send
</form>
</body>
</html>
i have the following html code:
<form class="dropzone" id="msform" enctype="multipart/form-data"> <!-- multistep form -->
<!-- progressbar -->
<ul id="progressbar">
<li class="active">Account Setup</li>
<li>Post an Image</li>
</ul>
<!-- fieldsets -->
<fieldset>
<h2 class="fs-title">Fill in Some General Details</h2>
<h3 class="fs-subtitle">As Simple As This</h3>
<input type="text" name="update" id="title" placeholder="Update Title" />
<textarea name="description" id="description" placeholder="Short Description/Add On"></textarea>
<input type="date" name="expire" id="expire" placeholder="Expire By" value="Expire By" />
<input type="button" name="next" class="next action-button" value="Next" />
</fieldset>
<fieldset>
<h2 class="fs-title">Upload Image</h2>
<h3 class="fs-subtitle">We currently only support images.</h3>
<div class="dropzone-previews dz-message" id="dropzonePreview">
</div>
<input type="button" name="previous" class="previous action-button" value="Previous" />
<input type="submit" name="submit" class="submit action-button" value="Submit"/>
</fieldset>
</form>
</div>
</div>
<script>
Dropzone.options.msform = { // The camelized version of the ID of the form element
// The configuration we've talked about above
url: "filepostupload.php",
autoProcessQueue: false,
autoDiscover: false,
addRemoveLinks: true,
uploadMultiple: false,
parallelUploads: 5,
maxFiles: 5,
paramName: "file",
previewsContainer: '.dropzone-previews',
clickable:'#dropzonePreview', //used for specifying the previews div
//used this but now i cannot click on previews div to showup the file select dialog box
// The setting up of the dropzone
init: function() {
var myDropzone = this;
this.element.querySelector("input[type=submit]").addEventListener("click", function(e) {
// Make sure that the form isn't actually being sent.
e.preventDefault();
e.stopPropagation();
if (myDropzone.getQueuedFiles().length === 0) {
var update = $('#title').val();
var description = $('#description').val();
var expiry = $('#expire').val();
var groupid = <?php echo $groupid ?>;
var request = $.ajax({
url: "updatesnofile.php",
type: "POST",
data: { update:update, description:description, expiry:expiry, groupid:groupid},
dataType:"text",
success: function(data) {
if (data=="success") {
alert('success');
} else {
alert(data);
}
},
error: function(request, err){
alert(err);
}
});
}else {
myDropzone.processQueue();
}
});
// Listen to the sendingmultiple event. In this case, it's the sendingmultiple event instead
// of the sending event because uploadMultiple is set to true.
this.on("sending", function() {
// Gets triggered when the form is actually being sent.
// Hide the success button or the complete form.
});
this.on("success", function(files, response) {
// Gets triggered when the files have successfully been sent.
// Redirect user or notify of success.
alert(response);
});
this.on("error", function(files, response) {
alert("error");
});
}
}
</script>
And my php script that does the file upload is :
<?php
session_start();
require 'config.php';
//I'm using mysql_ as an example, it should be PDO
$ds = DIRECTORY_SEPARATOR;
$foldername = "updatefiles/";
if (isset($_POST['update']) && isset($_POST['description']) && isset($_POST['expiry']) && isset($_POST['groupid'])){
$title= mysqli_real_escape_string($mysqli,trim($_POST['update']));
$description= mysqli_real_escape_string($mysqli,trim($_POST['description']));
$expire= mysqli_real_escape_string($mysqli,trim($_POST['expiry']));
$groupid= mysqli_real_escape_string($mysqli,trim($_POST['groupid']));
$fileupload = basename($_FILES['file']['name']);
$fileType = $_FILES['file']['type'];
$fileSize = $_FILES['file']['size'];
$tempFile = $_FILES['file']['tmp_name'];
$targetPath = dirname( __FILE__ ) . $ds. $foldername . $ds;
$targetFile = $targetPath. $fileupload;
move_uploaded_file($tempFile,$targetFile);
$fileupload = mysqli_real_escape_string($mysqli,basename($_FILES['file']['name']));
$fileType = mysqli_real_escape_string($mysqli,$_FILES['file']['type']);
$fileSize = mysqli_real_escape_string($mysqli,$_FILES['file']['size']);
mysqli_query($mysqli,"START TRANSACTION;");
$ins = mysqli_query($mysqli,"INSERT INTO posts (category, description, posttitle, userid, expire, group_id) VALUES ('updates','".$description."', '".$title."','{$_SESSION['userid']}', '".$expire."','".$groupid."' )");
if (!$ins) {
// fail
mysqli_query($mysqli,"ROLLBACK");
echo"error with first insert";
return FALSE;
}
$upd = mysqli_query($mysqli,"SET #post_id_in_posts = LAST_INSERT_ID()");
if (!$upd) {
// fail
mysqli_query($mysqli,"ROLLBACK");
echo"error with setting postid";
return FALSE;
}
$del = mysqli_query($mysqli, "INSERT INTO files (post_id,f_name, f_type, f_size) VALUES (#post_id_in_posts,'".$fileupload."', '".$fileType."', '".$fileSize."')");
if (!$del) {
// fail
mysqli_query($mysqli,"ROLLBACK");
echo "Error with Second Insert!";
return FALSE;
}
// All succeeded
mysqli_query($mysqli,"COMMIT");
echo"success";
return TRUE;
}else {
echo"formwasnotsubmitted";
}
?>
However, it keeps telling me that the form was not submitted (which means the posting of the form by drop zone fails, and therefore the data isn't posted over when there are files, the ajax works though when there are NO files), can anyone find out why? thanks!
I have managed to find the mistake, it is something to do with the way Dropzone sends the form data!
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'];
}
}
?>
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