Using Dropzone with Laravel 5.5 - php

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

Related

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

Drop file upload coming up as null in Laravel

I've got a form with a drag and drop file input, which I originally found here:
http://codepen.io/prasanjit/pen/NxjZMO
the form is as follows:
<form method="POST" action="{{ url('images/save') }}">
<div class="file-drop-area">
<span class="fake-btn">Choose file</span>
<span class="file-msg js-set-number">or drag and drop file here</span>
<input class="file-input" type="file" name="fileUpload">
</div>
<button>Save</button>
<input type="hidden" name="_token" value="{{ csrf_token() }}">
</form>
the JS is unchanged from the original pen:
$(document).ready(function () {
var $fileInput = $('.file-input');
var $droparea = $('.file-drop-area');
// highlight drag area
$fileInput.on('dragenter focus click', function() {
$droparea.addClass('is-active');
});
// back to normal state
$fileInput.on('dragleave blur drop', function() {
$droparea.removeClass('is-active');
});
// change inner text
$fileInput.on('change', function() {
var filesCount = $(this)[0].files.length;
var $textContainer = $(this).prev('.js-set-number');
if (filesCount === 1) {
// if single file then show file name
$textContainer.text($(this).val().split('\\').pop());
} else {
// otherwise show number of files
$textContainer.text(filesCount + ' files selected');
}
});
});
The problem is, when I pass this through a controller, the file comes up as null when using
$file = $request->file('fileUpload');
however, when using
$file = $request->get('fileUpload');
and then die dumping $file, it turns out that the get request is actually getting the username. So it'll die dump something like "image01.jpg".
Furthermore, when adding validation to the form,
$this->validate($request, [
'fileUpload' => 'required',
]);
the form will only go through after you've attached a file.
So what's going on? Why is this coming up as null on a file request?
<form method="POST" action="{{ url('images/save') }}" enctype="multipart/form-data">

Getting file out of url with php

So I give my users the possibility to upload a xml file of their iTunes playlist. Once they've uploaded their xml-file, i need to read out that xml file. I tried it first with just an ajax call and a local xml file and it worked fine, but now i need to get acces to the uploaded xml file.
This is my upload form
<form id="formulier" action="playlist.php" method="post" enctype="multipart/form-data">
<fieldset>
<legend>Upload your playlist</legend>
</br>
<label>
<input type="file" name="bestand">
</label>
</br>
</br>
<input type="submit" value="Generate">
</fieldset>
this is my playlist.php file:
<?php
$path = "playlists/" . ($_FILES['bestand']['name']);
if(move_uploaded_file($_FILES['bestand']['tmp_name'], $path)){
}
header("Location:index.html?url=".$path);
?>
this is my ajax call that i previously used:
var my_fn = function(callback) { // <-- this is callback to be called later
var jax = [];
$.ajax({
url: "",
dataType: "xml",
success: function (data) {
var song = $(data).find('key').filter(function () {
return $(this).text().indexOf('Name') != -1;
}).each(function() {
var content = $(this).next('string').text();
jax.push(content);
});
callback(jax);
}
});
};
How do I get to read out the xml file that is uploaded by the user? I really do not have a clue...

Problem with moving file and saving file data blank

I have some problem here..
I use upload from on index.php and i use jquery (ajax) to save any information to mysql. I have 3 file index.php, savedata.php, jsSave.js
But when i use $_REQUEST file from savedata.php and result is blank response also in mysql table, i replace $_REQUEST and use $_FILES and have same result.
What i already try and use is code like below...
Index.php
<form class="myform" action="<?php $_SERVER['PHP_SELF'];?>" method="POST" name="myform" id="myform" enctype="multipart/form-data" style="width:350px;">
<li>
<label>Item Picture</label>
<div class="fileUpload btn btn-primary">
<span>Choose Image..</span>
<input type="file" name="cItemPicture" class="cItemPicture" id="cItemPicture"/>
</div>
<input type="hidden" name="cPic" id="cPic"/>
</li>
<li>
<img border="0" src="images/loading_transparent.gif" width="20" height="20" id="imgLoad">
&nbsp<button class="button_blue" id="butTblSave" type="submit" style="width: 81px; height: 33px">SAVE</button>
</li>
and for savedata.php file script is
<?php
if($_REQUEST)
{
***$cItemPicture=$_FILES["cItemPicture"]["name"];***
$sql="INSERT INTO tblData(item_image) VALUES ('$cItemPicture')";
$result=mysql_query($sql) or die('Cannot Connect To SQL Server, Please contact your administrator');
move_uploaded_file($_FILES["cItemPicture"]["tmp_name"],
"upload/" . $_FILES["cItemPicture"]["name"]);
}
?>
last file which work as AJAX using jQuery file is jsSave.js
$(document).ready(function() {
$('#imgLoad').hide();
$('#msgConfirm').hide();
$('#tblAvailabilityResult').hide();
});
$(function() {
$("#butTblSave").click(function() {
$.ajax({
type: 'POST',
url: 'saveData.php',
data: $('form').serialize(),
beforeSend: function() {
$("imgLoad").show();
},
complete: function() {
$("imgLoad").hide();
},
cache: false,
success: function () {
$("#cItemPicture").val('');
$('#imgLoad').hide();
$('#butTblSave').attr("disabled", false);
$('#msgConfirm').fadeIn(500).delay(5000).fadeOut(1000);
$("#msgConfirm").html(' Add New Item Success.');
}
});
return false;
}
});
});
Do i miss something? when press SAVE button ajax reponse blank and saved data into mysql item_image also blank, also and no file moved into upload folder.
Any idea for this problem? Many thanks about this.
Thank you
try preventing the default submission of the form.
Because the form is submitting to SELF (index.php)
$("#butTblSave").click(function(event) {
event.preventDefault();
...

Ajax File Uploads

I have the following form:
<form method="post" enctype="multipart/form-data" id="upload" action="upload.php">
<input type="file" id="file" name="file" size="10"/>
<input id="uploadbutton" type="button" value="Upload"/>
</form>
The following Javascript:
$(document).ready(function () {
$("#uploadbutton").click(function () {
var filename = $("#file").val();
$.ajax({
type: "POST",
url: "upload.php",
enctype: 'multipart/form-data',
data: {
file: filename
},
success: function (text) {
alert("Data Uploaded: " + text);
}
});
});
});
and the following PHP (as a test)
echo json_encode($_POST); //uses post to check as $_FILES returns nothing
the alert will then notify me with the response line "file: test.jpg" as you can see though this is a file name and not the actual file itself. How can i convert my file to get the actual file rather then the name of the file.
Thank you in advance.
You still can use the "PUT" method instead of the "POST" method, it will work for all browsers except the old ones.
See : Topic
The syntax you are using is wrong for uploading files with ajax, you would need to pass a FormData object as the data of the request and use processData: false. However, some browsers don't support FormData, therefore you'll have to fallback to posting to a hidden iframe in those browsers.

Categories