Combine normal form with Dropzone - php

I am creating a drop zone form using dropzone.js. I firstly set the form up to automatically upload the file this worked fine, but I adapted the form to work only when the user submitted the data, i added file called custom_dropzone.js and the form appeared to work but the files never got uploaded to the folder.
HTML CODE (index.php)
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
<head>
<link href="css/dropzone.css" type="text/css" rel="stylesheet" />
<script src="dropzone.min.js"></script>
<script src="custom_dropzone.js"></script>
<!-- Now setup your input fields -->
<input type="email" name="username" />
<input type="password" name="password" />
<button type="submit">Submit data and files!</button>
</form>
</body>
</html>
upload.php
<?php
$ds = DIRECTORY_SEPARATOR; //1
$storeFolder = '../upload_test/uploads'; //2
if (!empty($_FILES)) {
$tempFile = $_FILES['file']['tmp_name']; //3
$targetPath = dirname( __FILE__ ) . $ds. $storeFolder . $ds; //4
$targetFile = $targetPath. $_FILES['file']['name']; //5
$allowed = array('gif','png' ,'jpg');
$filename = $_FILES['file']['name'];
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if(!in_array($ext,$allowed) ) {
echo 'error';
}
move_uploaded_file($tempFile,$targetFile); //6
}
?>
NEW JS custom.dropzone.js which seems to break the upload.php function
Dropzone.options.myAwesomeDropzone = { // The camelized version of the ID of the form element
// The configuration we've talked about above
autoProcessQueue: false,
uploadMultiple: true,
parallelUploads: 3,
maxFiles: 3,
previewsContainer: ".dropzone-previews",
accept: function(file, done) {
console.log("uploaded");
done();
},
init: function() {
this.on("maxfilesexceeded", function(file){
alert("No more files please!");
});
},
// The setting up of the dropzone
init: function() {
var myDropzone = this;
// First change the button to actually tell Dropzone to process the queue.
this.element.querySelector("button[type=submit]").addEventListener("click", function(e) {
// Make sure that the form isn't actually being sent.
e.preventDefault();
e.stopPropagation();
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("sendingmultiple", function() {
// Gets triggered when the form is actually being sent.
// Hide the success button or the complete form.
});
this.on("successmultiple", function(files, response) {
// Gets triggered when the files have successfully been sent.
// Redirect user or notify of success.
});
this.on("errormultiple", function(files, response) {
// Gets triggered when there was an error sending the files.
// Maybe show form again, and notify user of error
});
}
}
thanks for a lll your help. I just need the file to be uploaded, every thing else seems to work fine

You forgot to add enctype='multipart/form-data' to your <form> as an attribute and the method type as POST.
Add like this..
<form id="my-awesome-dropzone" method='post' class="dropzone" action="upload.php" enctype='multipart/form-data'>

With dropzone it seems that you do not need
method='post'
enctype='multipart/form-data'
like what was mentioned by Shankar … but thank you
I resolved this by commenting out the below line of js from custom_dropzone.js
//uploadMultiple: true,

Related

How to upload multiple files using dropzone.js?

My problem is when I drag & drop multiple files that time each image is called a particular ajax. I want to multiple file upload time only one ajax call.
I want to choose a single file and drag & drop it in dropzone and another file drag & drop so as not to replace the file with to first one I need both theme and click on the button that time save in the folder at one time ajax call.
Here is my code
HTML file
<link href="https://cdnjs.cloudflare.com/ajax/libs/dropzone/4.0.1/min/dropzone.min.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/dropzone/4.2.0/min/dropzone.min.js"></script>
<div class="row">
<form action="route.php?actionPresubmission=loanPreSubmission" class="form-horizontal dropzone" id="imageform">
</form>
</div>
route.php
$uploadDir = 'upload';
if (!empty($_FILES)) {
$tmpFile = $_FILES['file']['tmp_name'];
$filename = $uploadDir.'/'.time().'-'. $_FILES['file']['name'];
move_uploaded_file($tmpFile,$filename);
}
Thanks
Interpreting the question, I think you want to upload multiple files through one call.
For that, you need to stop autoProcessQueue which is true by default
Script:
Dropzone.options.myDropzone = {
autoProcessQueue: false, //This stops auto processing
acceptedFiles:".png,.jpg", //Change it according to your requirement.
init: function(){
var submit = document.querySelector('#submit');
mydropzone = this;
submit.addEventListener("click", function(){
mydropzone.processQueue();
});
this.on("success", function(file,response){
alert(response);
});
},
};
HTML:
<form action="upload.php" class="dropzone" id="myDropzone"></form>
<div>
<button type="button" class="btn btn-info" id="submit">Upload</button>
</div>
PHP
<?php
$folderName = 'upload/';
if(!empty($_FILES))
{
$file = $_FILES['file']['tmp_name'];
$fileLocation = $folderName . $_FILES['file']['name'];
move_uploaded_file($file,$fileLocation);
} ?>
Hope this helped you :)

Using Dropzone with Laravel 5.5

I would like to implement Dropzone in my long form. All tutorials focus on image upload ONLY, there are no tutorials if you have other stuff in your form. I am stuck in displaying dropzone. I have linked css and js files in my layout file but I still get an unstylized box for image upload and error in console: No URL provided.
This is a part of my form that should display Dropzone:
<form action="/ads/new" method="post" enctype="multipart/form-data">
<input class="input" type="text" name="name">
<input name="file" type="file" class="dropzone" multiple />
I would appreciate any help. Thanks.
UPDATE: I googled all the examples for this uploader and they all have only image upload field and nothing else. I need a solution when I have actually more fields in the form. Class dropzone can't be on whole form because I have more fields in it This is not just an image uploader!
I tried with this:
Dropzone.autoDiscover = false;
$("#pics").dropzone({
url: '/ads/new',
maxFilesize: 1
});
And there are no errors but whole dropzone functionality is gone.
Btw. If you don't know how to help then there is no need to downvote.
Try this might be help you
<form action="/ads/new" method="post" enctype="multipart/form-data" class="dropzone">
<input class="input" type="text" name="name">
<input name="file" type="file" multiple />
To make dropzone work in Laravel you can use the example below. Change it to your desired behaviour of course.
HTML
<form id="my-awesome-dropzone" class="dropzone"></form>
JQuery
<script type="text/javascript">
Dropzone.autoDiscover = false;
$(document).ready(function(){
var baseUrl = "{{ url('/') }}";
var token = "{{ Session::token() }}";
$("#my-awesome-dropzone").dropzone({
paramName: 'file',
url: baseUrl+"/ads/new",
params: {
_token: token
},
dictDefaultMessage: "Drop or click to upload images",
clickable: true,
maxFilesize: 2,
addRemoveLinks: true,
removedfile: function(file) {
// #TODO : Make your own implementation to delete a file
},
queuecomplete: function() {
// #TODO : Ajax call to load your uploaded files right away if required
}
});
});
</script>
Laravel Upload Function for route: /ads/new
use Illuminate\Support\Facades\File; // Required Dependencies
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\Input;
public function upload() {
$destinationPath = public_path() . '/uploads/'; // upload folder, set whatever you like
$fileNameWithExtension = Input::file('file')->getClientOriginalName();
$upload_success = Input::file('file')->move($destinationPath, $fileNameWithExtension); // uploading file to given path
if ($upload_success) {
return Response::json('success', 200);
} else {
return Response::json('error', 400);
}
}

HTML prevent from redirect upload php

I need to prevent the page redirected to the upload php when click upload button.
How can I do this in below code.
<form id="myForm" action="http://example/DB_1/AccessWeb/file_upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload1">
</form>
<button onclick="myFunction()"> Upload
</button>
<script>
function myFunction(){
document.getElementById("myForm").submit();
}
</script>
A very basic, quickly written example of how to send a file - using ajax to the same page so that the user doesn't get redirected. This is plain vanilla javascript rather than jQuery.
The callback function can do more than print the response - it could, for instance, be used to update the DOM with new content based upon the success/failure of the upload.
<?php
$field='fileToUpload';
if( $_SERVER['REQUEST_METHOD']=='POST' && !empty( $_FILES ) ){
$obj=(object)$_FILES[ $field ];
$name=$obj->name;
$tmp=$obj->tmp_name;
$size=$obj->size;
$error=$obj->error;
$type=$obj->type;
if( $error==UPLOAD_ERR_OK ){
/*
This is where you would process the uploaded file
with various tests to ensure the file is OK before
saving to disk.
What you send back to the user is up to you - it could
be json,text,html etc etc but here the ajax callback
function simply receives the name of the file chosen.
*/
echo $name;
} else {
echo "bad foo!";
}
exit();
}
?>
<!doctype html>
<html>
<head>
<title>File Upload - using ajax</title>
<script>
document.addEventListener('DOMContentLoaded',function(e){
var bttn=document.getElementById('bttn');
bttn.onclick=function(e){
/* Assign a new FormData object using the buttons parent ( the form ) as the argument */
var data=new FormData( e.target.parentNode );
var xhr=new XMLHttpRequest();
xhr.onload=function(e){
document.getElementById('status').innerHTML=this.response;
}
xhr.onerror=function(e){
alert(e);
}
xhr.open('POST',location.href,true);
xhr.send(data);
};
},false);
</script>
</head>
<body>
<form method='post' enctype='multipart/form-data'>
Select image to upload:
<input type='file' name='fileToUpload'>
<input type='button' id='bttn' value='Upload' />
</form><div id='status'></div>
</body>
</html>
Using JQuery AJAX methods will allow you to send and receive information to a specified url without the need to refresh your page.
You will need to include the JQuery library in your HTML page aswell. You can either download it and put it in your project folder or include an online library here, like so:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
So your form will now look like this:
<form id="myForm" method="post" >
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload1">
<input type="submit">
</form>
Then you can use this code to simply upload your image to your file upload page (tested and working for myself):
<script>
$(document).ready(function ()
{
$("#myForm").submit(function (e)
{
//Stops submit button from refreshing page.
e.preventDefault();
var form_data = new FormData(this);
$.ajax({
url: 'http://example/DB_1/AccessWeb/file_upload.php', //location of where you want to send image
dataType: 'json', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function (response)
{
alert('success');
},
error: function ()
{
alert('failure');
}
});
});
});
</script>
use AJAX With jQuery
$("#myForm").submit(function()
{
var formData = new FormData(this);
$.post($(this).attr("action"), formData, function(response) {
//Handle the response here
});
return false;
});

posting text file thru jQuery ajax in php and download the response file

Requirement:
I have to submit a form in a PHP file which has a file type input. I need jQuery ajax to post this text file to lets say processFile.php
processFile.php will take this text file as input and after processing will return a csv file which I want to download at the client.
I have seen many posts but nothing is helping me out.
HTML:
<form id="utilityForm" class="utilityForm4" method="POST" enctype="multipart/form-data" style="margin-top:25px">
<input type="file" name="image" id="image"/>
<br/><input type="submit" name="download" class="submit" value="Submit"/>
</form>
jQuery:
$(document).ready(function(){
$(".submit").click(function(e){
var urlstring = "processFile.php"
var form_data = new FormData($(this)[0]);
$.ajax({
url : urlstring,
type: "POST",
data : postData,
success:function(result){
var uri = 'data:application/csv;charset=UTF-8,' + encodeURIComponent(result);
window.open(uri, 'result.csv');
},
error: function(jqXHR, textStatus, errorThrown)
{
alert('failed');
echo (errorThrown);
}
});
});
});
I have tried hundreds of solutions given on the net but none is working.
Here I am providing complete working example:
HTML File:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function (e) {
$("#uploadimage").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "ajax_php_file.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false
success: function(result) // A function to be called if request succeeds
{
e.preventDefault(); //stop the browser from following
window.location.href = 'upload/'+result;
}
});
}));
// Function to preview image after validation
});
</script>
</head>
<body>
<form id="uploadimage" action="" method="post" enctype="multipart/form-data">
Download
<input type="file" name="file" id="file" required />
<input type="submit" value="Upload" class="submit" />
</form>
</body>
PHP File:
<?php
if(isset($_FILES["file"]["type"]))
{
$temporary = explode(".", $_FILES["file"]["name"]);
$file_extension = end($temporary);
if (file_exists("upload/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " <span id='invalid'><b>already exists.</b></span> ";
}
else
{
$sourcePath = $_FILES['file']['tmp_name']; // Storing source path of the file in a variable
$targetPath = "upload/".$_FILES['file']['name']; // Target path where file is to be stored
move_uploaded_file($sourcePath,$targetPath) ; // Moving Uploaded file
echo $_FILES["file"]["name"];
}
}
else
{
echo "<span id='invalid'>***Invalid file Size or Type***<span>";
}
?>
Try to upload any file.
Is this useful for you?

Empty $_FILES while AJAX Uploading

I Have got the Following Problem:
I'm trying to Upload a File via a Form over Ajax
Here is the HTML File:
<html>
<header>
<link rel="stylesheet" href="useme.css"/>
<script src="jq.js"></script>
<script src="actions.js"></script>
</header>
<body>
<form enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="30000000" />
<input type="file" id="file" name="file"/>
<input type="button" value="Click" id="submitBtn"/>
</form>
<span class="status">no status</span>
</body>
The JavaScript File:
/**
* Created by Kenny on 12.04.2015.
*/
$(document).ready(function(){
$("#submitBtn").click(function(){
var filename = $("#file").serialize();
$.ajax({
processData: false, // tell jQuery not to process the data
contentType: false, // tell jQuery not to set contentType
url: "upload.php",
enctype: 'multipart/form-data',
data : {
file: filename
},
type : "POST",
success: function(data){
if(data != "fail")
$(".status").html("Upload is availible at: " + data);
else
$(".status").html("Upload failed.");
}
});
});
});
And last but not lately the PHP File that does the Magic (Not really atm)
<?php
/**
* Created by PhpStorm.
* User: Kenny
* Date: 12.04.2015
* Time: 23:55
*/
$uploaddir = '/many/upload/' . uniqid() . '/';
if(!file_exists($uploaddir)){
mkdir($uploaddir, 0777, true);
}
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
echo "http://use.hints.me/" . $uploaddir;
file_put_contents($uploaddir . "/index.php", "<?php Header('Location: " . basename($_FILES['userfile']['name']) . "'); ?>");
} else {
echo "fail";
}
?>
My Problem here is that I only get empty $_FILES in the PHP-File, the PHP File somehow works fine when i use a Standard POST form, but with Ajax it doesnt work at all.
Excuse my messy Code, it's just a Proof of Concept to a friend of mine and not at all used for Providing a serious File Upload site. I just want to get this working.
Things i checked here before:
check the php.ini File if the File Upload is enabled
added enctype="multipart/form-data" to the Form
added the MAX_FILE_SIZE tag to the Form
checked StackOverFlow all over

Categories