I have been trying to make this dropzone.js work on a client's website and it doesn't seem to be working.
When I upload a file it doesn't upload to the photo folder and doesn't get added to the database.
The page to upload the files is in www.sunkyog.com/admin/dd.php [sample page I created], the PHP page is www.sunkyog.com/admin/up.php and the folder to upload to is www.sunkyog.com/photos.
This is my code:
dd.php
<head>
<!-- 1 -->
<link href="css/dropzone.css" type="text/css" rel="stylesheet" />
<!-- 2 -->
<script src="../js/dropzone.js"></script>
</head>
<body>
<form action="http://sunkyog.com/admin/up.php" enctype="multipart/form-data" class="dropzone" id="photoUploadDropzone"></form>
<script type="text/javascript">
Dropzone.options.photoUploadDropzone = {
paramName: "file",
maxFilesize: 5, // MB
maxFiles: 10,
addRemoveLinks: true,
acceptedFiles: "image/jpeg, image/jpg, image/png, image/gif",
accept: function(file, done) {
done();
}
};
</script>
</body>
</html>
up.php
if (!empty($_FILES)) {
$tempFile = $_FILES['file']['tmp_name'];
$targetPath = "photos/";
$targetFile = $targetPath. $_FILES['file']['name'];
move_uploaded_file($tempFile,$targetFile);
mysql_query("INSERT INTO club_photos VALUES('','photos/$tempFile','$fk_id')");
}
?>
You can go to the page http://www.sunkyog.com/admin/dd.php to try for yourself and then after uploading navigate to http://www.sunkyog.com/photos/yourFileName to see if it uploaded.
<script src="dropzone.js"></script>
<script type="text/javascript">
Dropzone.autoDiscover = false;
var myDropzone = new Dropzone("#form_id");
myDropzone.options.addRemoveLinks=true;
myDropzone.options.uploadMultiple=false;
myDropzone.options.autoProcessQueue=false;
myDropzone.options.url='system_message_process.php';
myDropzone.options.maxFiles=1;
myDropzone.options.acceptedFiles='image/*';
function submit(){
myDropzone.processQueue();
myDropzone.on("success", function(file,responsenew) {
// alert(responsenew);
var response = jQuery.parseJSON(responsenew);
});
}
</script>
Please check it for submit manually or else set autodiscover as true also processQueue as true and check once again along firebug request sent or not. its working fine for me
Related
I needed a code to upload images to the web application and I did it using the following example:
source
the code works fine on localhost on apache. Now I want to convert the image file to the same base64 while uploading it to the server. I couldn't find how to modify the code for this. Can anyone help? Thanks.
This is upload.php:
<?php
/* get the name of the uploaded file */
$filename = $_FILES['file']['name'];
/* choose where to save the uploaded file */
$location = "upload/".$filename;
/* save the upploaded file to the local filesystem */
if ( move_uploaded_file($_FILES['file']['tmp_name'], $location) ) {
echo 'Success';
} else {
echo'Failure';
}
?>
and this is uploader.html
<!DOCTYPE html>
<html>
<head>
<title> Ajax JS F Up Example </title>
</head>
<body>
<!-- HTML5 Input Form Elements -->
<input id="fileupload" type="file" name="fileupload" />
<button id="upload-button" onclick="uploadFile()"> Upload </button>
<!-- Ajax JS File Up Logic-->
<script>
async function uploadFile() {
let formData = new FormData();
formData.append("file", fileupload.files[0]);
await fetch('/upload.php', {
method: "POST",
body: formData
});
alert('File uploaded.');
}
</script>
</body>
I want to save the screenshot to server when click on div on page. It's a few problems. I'm rookie. Please help.
1)The picture is being saved but also shown at the bottom of the page. just want to be saved.
2)This is the most important. page contains iframe and image files. my main goal is to take images of them. but I was not successful. please help.
my html file
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>title</title>
</head>
<body>
<div id="mydiv">
here is iframe
</div>
<div>
bla bla bla
image
</div>
<script type="text/javascript" src="html2canvas.js"></script>
<!-- Script -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
var mydiv = document.getElementById('mydiv');
mydiv.style.cursor = 'pointer';
mydiv.onclick = function () {
html2canvas(document.body).then(function(canvas) {
document.body.appendChild(canvas);
// Get base64URL
var base64URL = canvas.toDataURL('image/jpeg').replace('image/jpeg', 'image/octet-stream');
// AJAX request
$.ajax({
url: 'ajaxfile.php',
type: 'post',
data: {image: base64URL},
success: function(data){
console.log('Upload successfully');
}
});
});
};
mydiv.onmouseover = function() {
this.style.backgroundColor = 'white';
};
mydiv.onmouseout = function() {
this.style.backgroundColor = '';
};
</script>
</body>
</html>
please edit the code for me. how it works the way I want.
ajaxfile.php I have no problem with this
<?php
$image = $_POST['image'];
$location = "upload/";
$image_parts = explode(";base64,", $image);
$image_base64 = base64_decode($image_parts[1]);
$filename = "screenshot_".uniqid().'.png';
$file = $location . $filename;
file_put_contents($file, $image_base64);
I'm using summernote html text editor on my site. I want to download images to my server when user put an image url to Image URL area then press to Insert Image button.
Currently summernote only get image's source for src attribute. I want to store images on my own Amazon S3 Bucket or VPS.
There are many docs about summernote image upload but all of them for upload from pc not from URL.
How can I overwrite this feature?
Image dialog
So since you are not able to read dataUrl of cross-origin images in your client-side script the decision is to get url from Image URL area and send it to your backend. There you may use a simple php script to download the image.
The example includes both client and backend codes. Both tested. All you need is to put these two scripts to one of your web server's directories and give it a try.
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Summernote</title>
<!-- include libraries(jQuery, bootstrap) -->
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.css" rel="stylesheet">
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.js"></script>
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.js"></script>
<!-- include summernote css/js-->
<link href="http://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.2/summernote.css" rel="stylesheet">
<script src="http://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.2/summernote.js"></script>
</head>
<body>
<div id="summernote">Hello Summernote</div>
<script type="text/javascript">
$(document).ready(function() {
$('#summernote').summernote();
$('button[data-original-title="Picture"]').click(function(){
// Set handler on Inset Image button when dialog window is opened
$('.modal-dialog .note-image-btn').one('click', function(e) {
// Get Image URL area
var imageUrl = $('.modal-dialog .note-image-url').val();
// Send it to your backend
$.ajax({
url: "image_loader.php",
data: "url="+imageUrl,
type: "POST",
dataType: 'json'
}).success(function(data) {
if (typeof data[0] === 'string') {
$('img[src="'+imageUrl+'"]').attr('src', data);
} else {
// What to do if image downloading failed
window.alert('oops');
}
}).error(function() {
// What to do if ajax request failed
window.alert('oops');
});
});
});
});
</script>
</body>
</html>
image_loader.php
<?php
if ($_POST['url']) {
// Here you'd better put some logic to check that $_POST['url'] is a correct url before use it
$image = file_get_contents($_POST['url']);
if ($image) {
// Put downloaded image on your server
$file = fopen('imagename.jpeg', 'w');
fwrite($file, $image);
fclose($file);
}
/**
* Now your code needs to echo one of the following:
* string Url of an uploaded image on your server
* bool False if it failed
*
* To avoid bool to string conversion during output response needs to be sent as JSON
*/
$response = ($image) ? array('/PATH_TO_IMAGE_DIRECTORY_IF_NEEDED/imagename.jpeg') : array(false);
echo json_encode($response);
}
For example with this image https://imgsnap.com/images/2015/02/23/abstract_0005.jpg
UPDATE (to your comment about img styling)
Put the following line in summernote.js to trigger a special event when image url has been handled by the editor.
$(document).trigger('imageUrlInserted', src);
Put it on line 4095 (according to my version of file) inside of insertImage() method before
$image.css('width', Math.min($editable.width(), $image.width()));
Now in index.php inside of
$('.modal-dialog .note-image-btn').one('click', function(e) {
...
...
});
replace all the code with this
// Get Image URL area
var imageUrl = $('.modal-dialog .note-image-url').val();
// Send it to your backend after the image been handled by the editor
$(document).on('imageUrlInserted', function(e, sourceUrl) {
if (sourceUrl === imageUrl) {
$.ajax({
url: "image_loader.php",
data: "url="+imageUrl,
type: "POST",
dataType: 'json'
}).success(function(data) {
if (typeof data[0] === 'string') {
$('img[src="'+imageUrl+'"]').attr('src', data).removeAttr('style');
} else {
// What to do if image downloading failed
window.alert('oops');
}
}).error(function() {
// What to do if ajax request failed
window.alert('oops');
});
}
});
I have successfully sent a csrf token using dropzone but using jquery style, now I don't want to use any jquery in my code I want to use javascript style to get the csrf token. I tried using below code but it keeps on giving me the tokenmismatch error,
myDropzone.on("sending", function(file,xhr,formData) {
// Show the total progress bar when upload starts
var folname = document.getElementById('folname').value;
var token = document.getElementsByName("_token")[0].value;
formData.append('folname',folname);
formData.append('_token', token );
});
this is the code that is working using jquery.
myDropzone.on("sending", function(file,xhr,formData) {
// Show the total progress bar when upload starts
var folname = document.getElementById('folname').value;
formData.append('folname',folname);
formData.append('_token', $('input[name="_token"]').val() );
});
any advice is appreciated. thanks guys.
Plain old inline javascript variable perhaps? Placed before all scripts possibly at the head
var csrf_token = "{{ csrf_token() }}";
...
// js file where dz related code is residing
...
myDropzone.on("sending", function(file,xhr,formData) {
// Show the total progress bar when upload
var folname = document.getElementById('folname').value;
formData.append('folname',folname);
formData.append('_token', csrf_token);
});
Guys thank you for leading me to the right path. I found the problem, I have two elements with "_token" name. so when debugging it returns 'undefined' error.
this code now works.
var token = document.getElementsByName("_token")[0].value;
my csrf token declaration is like this
<form name="post_form" id="post_form" class="form-horizontal" role="form" method="POST" action="/post">
{!! csrf_field() !!}
<!-- other code input boxes -->
</form>
<!--my dropzone code is below the form-->
<script>
// dropzone code here
</script>
the solution is either I use the token in my meta tag to my dropzone submission or change the name of the meta tag name from "_token" to something else.
so for this, I choose to use the meta tag to my dropzone code and it's now working. please see below for the solution.
I added a meta tag in my header with "_token" name.
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="_token" content="{!! csrf_token() !!}"/>
</head>
and in my footer
<script type="text/javascript">
$.ajaxSetup({
headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') }
});
</script>
</body>
</html>
I have use the meta tag token value instead. here's what I did.
myDropzone.on("sending", function(file,xhr,formData) {
// Show the total progress bar when upload starts
var folname = document.getElementById('folname').value;
var token1 = document.getElementsByTagName('meta')['_token_'].getAttribute('content');
formData.append('folname',folname);
formData.append('_token', token1 );
});
let me know if I should add anything else to make the post more useful.
There are two ways to solve it.
--- FIRST (easiest) ---
<form method="POST" action="/your/url/here" class="dropzone" id="upload-files" enctype="multipart/form-data">
{{ csrf_field() }}
{{ method_field('POST') }}
</form>
<script>
$(function() {
Dropzone.options.uploadFiles = {
paramName: 'document_files',
maxFilesize: 3,
init : function() {
this.on("success", function(file, response) {
// file uploaded successfully
});
}
};
});
</script>
--- SECOND ---
Using dropzone in this way, you can place your dropzone inside another form.
<div class="dropzone dropzone-previews" id="dropzone-upload-documents"></div>
<script>
$(function() {
// in this case is important that autoDiscover = false
Dropzone.autoDiscover = false;
$("#dropzone-upload-documents").dropzone({
paramName: 'document_files',
maxFilesize: 3,
url: "/your/url/here",
init: function() {
this.on("success", function(file, response) {
// file uploaded successfully
});
},
sending: function(file, xhr, formData) {
formData.append("_token", "{{ csrf_token() }}");
formData.append("_method", "POST");
}
});
});
</script>
Valumes doesn't show UPLOAD button under Firefox (MVC3 Project).
It works fine under: IE, Chrome
I am going to kill myself but I don't understand why is it?
ANYYY CLUUU pleaseeee!
<script src="#Url.Content("~/Scripts/valums/FileUploader.js")" type="text/javascript"></script>
<div id="fileUploader">
<noscript>
<p>
Please enable JavaScript to use file uploader.</p>
<!-- or put a simple form for upload here -->
</noscript>
</div>
.................
var button = $('#fileUploader')[0];
var uploader = new qq.FileUploader({
element: button,
allowedExtensions: ['jpg', 'jpeg', 'png', 'gif'],
sizeLimit: 2147483647,
action: '#Url.Action("UploadFile")',
multiple: false,
onComplete: function (id, fileName, responseJSON) {
var uploadedFile = "/Images/Orders/thumb-" + responseJSON.uploadedFile;
$("#uploadedImage").attr("src", uploadedFile);
$("#ImageErrorMessage").text("");
}
});
Just put the VALUMS code within $(document).ready(function () { // here });
and keep it under the <HEAD> tag. That's it!