How to save the image(uploaded from Dropbox Chooser) to the folder? - javascript

I know you think this as a silly question. But I am not able to get it done. I am using dropbox chooser to upload the images form user's dropbox account. Once they upload it, I am able to save it in the database, but I am not able to save it in the uploads folder. Following is my code:
Index.php
<form class="form" method="post" enctype="multipart/form-data" >
<div id="dropbox-container"></div>
<input id="dropbox_image" name="image" type="hidden" />
<button type="submit" class="button">Save</button>
</form>
<script type="text/javascript" src="https://www.dropbox.com/static/api/2/dropins.js" id="dropboxjs" data-app-key="wgiv8kvzvq57mlw"></script>
<script type="text/javascript">
options = {
success: function(files) {
files.forEach(function(file) {
add_img_to_list(file);
document.getElementById('dropbox_image').value = file['name'];
});
},
cancel: function() {
//optional
},
linkType: "preview", // "preview" or "direct"
multiselect: true, // true or false
extensions: ['.png', '.jpg'],
};
var button = Dropbox.createChooseButton(options);
document.getElementById("dropbox-container").appendChild(button);
function add_img_to_list(file) {
var li = document.createElement('li');
var a = document.createElement('a');
a.href = file.link;
var img = new Image();
var src = file.thumbnailLink;
img.src = src;
img.className = "th"
document.getElementById("img_list").appendChild(li).appendChild(a).appendChild(img);
}
</script>
hController.php
<?php
$fileName = $_POST['image'];
$tmpName = $_POST['image'];
$image = new \Model\Upload_Picture();
$image->image = $_POST['image'];
$fileName = uniqid()."_".basename($fileName);
$fileName = str_replace(' ', '_', $fileName);
$fileName = str_replace('-', '_', $fileName);
move_uploaded_file(tmpName, UPLOAD_PATH . 'pictures/'. $fileName );
$image->save();
?>
This code helps me to save the image into the database, but not storing it in the upload folder. I think I am making a mistake in some piece of code, help will be appreciated. Also if I upload multiple images from the dropbox account, I am not able to store all of them in my database. Only the last one is stored in db.

Related

How to Convert SVG to image (JPEG, PNG, etc.) in the browser and save on server for product preview to checkout

I'm converting svg using html2canvas to save on server side as png product preview before checkout with base64. The svg works fine. It's for a customized item checkout. The problem is after customization and checkout is clicked, the svg image does not save to preview on checkout page before checking out. Reason is i don't what to write to for the php to save it. I need help in writing the php code for "savetoserver.php" to save to server
function imagetopng(){
function showCheckout() {
$("#checkoutcontainer").show();
$(".productoverview").show();
$("#popup").show();
}
setTimeout(showCheckout, 500);
html2canvas($(".stole"), {
allowTaint: true,
letterRendering: true,
onrendered: function(canvas) {
$('.stole-png').prepend(canvas);
var dataURL = canvas.toDataURL('image/png', 1.0);
$.ajax({
type: "POST",
url: "savetoserver.php",
data: {
imgBase64: dataURL
}
})
.done(function(o) {
var fileurl = o;
var websiteurl = "http://woven.indexsta.com/";
var formatted = websiteurl + fileurl;
//var formatted = "stole-designs/" + fileurl
$('#stole-url').attr('value', formatted);
$('#stolepreview').attr('src', fileurl);
// If you want the file to be visible in the browser
// - please modify the callback in javascript. All you
// need is to return the url to the file, you just saved
// and than put the image in your browser.
});
}
});
$('.stole-png').empty();
};
$('#closecheckout').on('click touch',function(){
$("#checkoutcontainer").css('display','none');
$("#popup").css('display','none');
});
I figured it out. Incase anyone faces same challenge, here's the script i wrote to solve it.
<?php
// requires php5+
// create directory
if (!file_exists('images/')) {
mkdir('images/', 0777, true);
}
define('UPLOAD_DIR', 'images/');
$img = $_POST['imgBase64'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = UPLOAD_DIR . uniqid() . '.png';
$success = file_put_contents($file, $data);
print $success ? $file : 'Unable to save the file.';
?>

Multiple images upload using javascript, PHP, MySQl

Here I am doing a Hybrid Android app conversion. My page is HTML page. I need to upload multiple images using Javascript only. In my page I can't use PHP if(isset($_POST['submit'])) function because it's a HTML page. And also I can't use <form action='upload.php' method='POST'>, because it redirect to that PHP page. So I can't be in a same page.
<form method="POST" action="" id="proinsert" name="proinsert" enctype="multipart/form-data">
<input type="file" name="photo" id="photo" class="form-control">
<button id="submit" name="submit" class="btn btn-primary margintop">Submit</button>
</form>
and my PHP page
foreach($_FILES['photos']['name'] as $file){
$message .= "Attachments:" .$file['filename'];
}
Your question is very broad. However, I'll do my best to answer it:
You have 3 logical layers to your problem here:
The HTML that creates the user interface
The Javascript - that handles processing and sending your images (or any file) to another place.
Your PHP code, which will accept your images and process/save them to your server.
A brief overview of how to approach the solution:
Build a form in HTML with a file upload field.
<form method="post" enctype="multipart/form-data">
<input type="file" name="files[]" multiple>
<input type="submit" value="Upload File" name="submit">
</form>
In your HTML file, write or include Javascript that will serialise the form data, and POST it to your PHP file.
<script type="text/javascript">
const url = 'process.php';
const form = document.querySelector('form');
form.addEventListener('submit', e => {
e.preventDefault();
const files = document.querySelector('[type=file]').files;
const formData = new FormData();
for (let i = 0; i < files.length; i++) {
let file = files[i];
formData.append('files[]', file);
}
// Uses browser's built in Fetch API - you can replace this with jQuery or whatever you choose.
fetch(url, {
method: 'POST',
body: formData
}).then(response => {
console.log(response);
});
});
</script>
Write the logic into a new PHP file (called process.php) to handle the form data (images) as appropriate.
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (isset($_FILES['files'])) {
$errors = [];
$path = 'uploads/';
$extensions = ['jpg', 'jpeg', 'png', 'gif'];
$all_files = count($_FILES['files']['tmp_name']);
$fileNames = [];
for ($i = 0; $i < $all_files; $i++) {
$file_name = $_FILES['files']['name'][$i];
$file_tmp = $_FILES['files']['tmp_name'][$i];
$file_type = $_FILES['files']['type'][$i];
$file_size = $_FILES['files']['size'][$i];
$file_ext = strtolower(end(explode('.', $_FILES['files']['name'][$i])));
$fileNames[] = $file_name;
$file = $path . $file_name;
if (!in_array($file_ext, $extensions)) {
$errors[] = 'Extension not allowed: ' . $file_name . ' ' . $file_type;
}
if ($file_size > 2097152) {
$errors[] = 'File size exceeds limit: ' . $file_name . ' ' . $file_type;
}
if (empty($errors)) {
move_uploaded_file($file_tmp, $file);
}
}
if ($errors) {
print_r($errors);
} else {
print_r(json_encode(['file_names' => $fileNames]));
}
}
}
For speed - the example code in this solution was taken from https://www.taniarascia.com/how-to-upload-files-to-a-server-with-plain-javascript-and-php/
For other examples - you could check out StackOverflow's other questions. Here's a similar one to yours: uploading image using javascript

Multiple File Upload actions for a single File Input PHP/JS

I want to upload different images from different folders in a single file upload form submit.
When I click the upload button for the second time before clicking the submit button, file input field get replace with the latest selections.
Is it possible to append the selections till the submit is clicked.
My JS code displays all the selected file. But submits only the last selections
Here is my HTML
<form name="status-form" id="status-form" method="post" enctype="multipart/form-data">
<input type='file' name='file1[]' id="upload-image" multiple />
<input type='hidden' name='file2' value="aaaaaaaa" />
<div id="upload-img">
<output id="list"></output>
</div>
<br/>
<button type="submit" name="submit" class="btn btn-info" id="status-btn">Send It!</button>
</form>
Here is my JS
var allImages = [];
if (window.FileReader) {
document.getElementById('upload-image').addEventListener('change', handleFileSelect, false);
}
function handleFileSelect(evt) {
var files = evt.target.files;
for (var i = 0; i < files.length; i++) {
var f = files[i];
var reader = new FileReader();
reader.onload = (function(f) {
return function(e) {
document.getElementById('list').innerHTML = document.getElementById('list').innerHTML + ['<img src="', e.target.result,'" title="', f.name, '" width="150" class="image-gap" />'].join('');
};
})(f);
reader.readAsDataURL(f);
}
var formData = $('form').serializeArray();
console.log(formData);
$.ajax({
type:'POST',
url: 'temp.php',
data:formData,
success:function(data){
//code here
},
error: function(data){
//code here
}
});
console.log(folder);
$('#upload-img').addClass('image-div');
}
And my PHP is just a var_dump for the moment
if (isset($_POST['submit'])) {
var_dump($_FILES['file1']);
var_dump($_POST['file2']);
}
You can try this:
Select file using browse field
call a method (setImage()) on onchange of this browse field
and in setImage():
function setImage(){
// Get the src value of browse field
// Create a new hidden browse field with src value of above browse
// field
// And set blank value of src of first one browse field
}
The idea is you select an image n times, the above method will create n hidden browse field in your html.
For example: If you select three images, then there will be four browse fields.
1 Shown to you
Other three are hidden
Now press submit and in server side you will get 4 file fields one with empty file and other three with files.
Ignore empty one and upload other three images.
With the hint given by Rahul I was able to make it work.
Here is the answer
JS File
var uploadImage = 0;
$( document ).ready(function() {
uploadImage = Math.floor(Date.now() / 1000);
});
if (window.FileReader) {
document.getElementById('upload-image').addEventListener('change', handleFileSelect, false);
}
function handleFileSelect(evt) {
var files = evt.target.files;
for (var i = 0; i < files.length; i++) {
var f = files[i];
var reader = new FileReader();
reader.onload = (function(f) {
return function(e) {
document.getElementById('list').innerHTML = document.getElementById('list').innerHTML + ['<img src="', e.target.result,'" title="', f.name, '" width="150" class="image-gap" />'].join('');
$('<input>').attr({
type: 'hidden',
id: uploadImage++,
name: uploadImage++,
value: e.target.result
}).appendTo('form');
console.log(e.target.result);
};
})(f);
reader.readAsDataURL(f);
}
$('#upload-img').addClass('image-div');
}
PHP Code
if (isset($_POST['submit'])) {
define('UPLOAD_DIR', 'images/');
$patterns = array('/data:image\//', '/;base64/');
foreach ($_POST as $key => $value) {
if (preg_match('/^(0|[1-9][0-9]*)$/', $key)) {
$imageData = explode(',', $value, 2);
$type = preg_replace($patterns, '', $imageData[0]);;
if (count($imageData) > 1) {
$img = str_replace($imageData[0].',', '', $value);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = UPLOAD_DIR . uniqid() . '.'.$type;
$success = file_put_contents($file, $data);
print $success ? $file : 'Unable to save the file.';
}
}
}
}
HTML Code
<form name="status-form" id="status-form" method="post" enctype="multipart/form-data">
<input type='file' name='file1[]' id="upload-image" multiple />
<div id="upload-img">
<output id="list"></output>
</div>
<br/>
<button type="submit" name="submit" class="btn btn-info" id="status-btn">Send It!</button>
</form>

Get URLs of multiple images uploaded via php

I have a Image upload form where in a user can upload Images and the after uploading a order no will be generated and the uploaded images will be shown.
My Upload Page has -
<h2>Upload Images here</h2>
<form enctype="multipart/form-data" action="" method="post">
First Field is Compulsory. Only JPEG,PNG,JPG Type Image Uploaded. Image Size Should Be Less Than 100KB.
<hr/>
<div id="filediv"><input name="file[]" type="file" id="file"/></div><br/>
<input type="button" id="add_more" class="upload" value="Add More Files"/>
<input type="submit" value="Upload File" name="submit" id="upload" class="upload"/>
</form>
<br/>
<br/>
<!-------Including PHP Script here------>
<?php include "upload.php"; ?>
Upload.php -
<?php
if (isset($_POST['submit'])) {
$j = 0; //Variable for indexing uploaded image
$target_path = "uploads/"; //Declaring Path for uploaded images
for ($i = 0; $i < count($_FILES['file']['name']); $i++) {//loop to get individual element from the array
$validextensions = array("jpeg", "jpg", "png"); //Extensions which are allowed
$ext = explode('.', basename($_FILES['file']['name'][$i]));//explode file name from dot(.)
$file_extension = end($ext); //store extensions in the variable
$target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext) - 1];//set the target path with a new name of image
$j = $j + 1;//increment the number of uploaded images according to the files in array
if (($_FILES["file"]["size"][$i] < 100000) //Approx. 100kb files can be uploaded.
&& in_array($file_extension, $validextensions)) {
if (move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {//if file moved to uploads folder
echo $j. ').<span id="noerror">Image uploaded successfully!.</span><br/><br/>';
} else {//if file was not moved.
echo $j. ').<span id="error">please try again!.</span><br/><br/>';
}
} else {//if file size and file type was incorrect.
echo $j. ').<span id="error">***Invalid file Size or Type***</span><br/><br/>';
}
}
}
?>
Javascript to let user add more images -
var abc = 0; //Declaring and defining global increement variable
$(document).ready(function() {
//To add new input file field dynamically, on click of "Add More Files" button below function will be executed
$('#add_more').click(function() {
$(this).before($("<div/>", {id: 'filediv'}).fadeIn('slow').append(
$("<input/>", {name: 'file[]', type: 'file', id: 'file'}),
$("<br/><br/>")
));
});
//following function will executes on change event of file input to select different file
$('body').on('change', '#file', function(){
if (this.files && this.files[0]) {
abc += 1; //increementing global variable by 1
var z = abc - 1;
var x = $(this).parent().find('#previewimg' + z).remove();
$(this).before("<div id='abcd"+ abc +"' class='abcd'><img id='previewimg" + abc + "' src=''/></div>");
var reader = new FileReader();
reader.onload = imageIsLoaded;
reader.readAsDataURL(this.files[0]);
$(this).hide();
$("#abcd"+ abc).append($("<img/>", {id: 'img', src: 'x.png', alt: 'delete'}).click(function() {
$(this).parent().parent().remove();
}));
}
});
//To preview image
function imageIsLoaded(e) {
$('#previewimg' + abc).attr('src', e.target.result);
};
$('#upload').click(function(e) {
var name = $(":file").val();
if (!name)
{
alert("First Image Must Be Selected");
e.preventDefault();
}
});
});
I have a table in my database which has the following fields -
Id - order_id - img_url
I don't know what loop should I create in my upload.php file to get this working -
User uploads images, then new order is created and order_id is generated which will then be updated as new entries to the table with the uploaded image urls.
Thanks

File doesn't always upload to server using PHP & Javascript

I have a page that I use to have users press a submit button to insert MYSQL data but also capture an image and upload a .png file to a directory all from the click of one submit button. 9/10 this works perfectly. I'm not sure if it's a connectivity issue (it's being done on a wireless device) or if it's my code. That 1/10 times it will INSERT the MYSQL data but it will not upload the image to the server. Below is my upload code from my file and the upload_data.php file that the code calls. Sorry my formatting on this site isn't the greatest.
<script>
function uploadEx() {
var canvas = document.getElementById("canvasSignature");
var dataURL = canvas.toDataURL("image/png");
document.getElementById('hidden_data').value = dataURL;
var fd = new FormData(document.forms["form"]);
var xhr = new XMLHttpRequest();
xhr.open('POST', '/inc/img/inspection/upload_data.php', true);
xhr.upload.onprogress = function(e) {
if (e.lengthComputable) {
var percentComplete = (e.loaded / e.total) * 100;
console.log(percentComplete + '% uploaded');
//alert('Succesfully uploaded');
}
};
xhr.onload = function() {
};
xhr.send(fd);
};
</script>
BELOW IS UPLOAD_DATA.PHP
<?php
$upload_dir = "upload/";
$img = $_POST['hidden_data'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$id = $_POST['sub_id'];
$file = $upload_dir . $id . ".png";
$success = file_put_contents($file, $data);
print $success ? $file : 'Unable to save the file.';
?>
Based on your comment, you are not cancelling the default submit event and that would cause the form to be submitted. And that could cause the ajax request to not finish always.
If you use inline javascript like you do (I would try to move all inline js to the script itself...), you need to make sure that you use something like:
onsubmit="return uploadEx();"
and
onclick="return uploadEx();"
And in your uploadEx() function you end with:
function uploadEx() {
// your code
return false;
}

Categories

Resources