How do I add a simple image upload feature? - javascript

I want to give my new website a feature where I can upload 1 image by a button and stores(local storage) the image on another .html page, then if I grab it's absolute URL I can post this on forums websites where it's preview will show, so far I have a function that let's me upload and preview an image.. But I want to go to another level.
HTML:
<input type="file" onchange="previewFile()"><br>
<img src="" height="200" alt="Image preview...">
Javascript:
<script>
function previewFile(){
var preview = document.querySelector('img'); //selects the query named img
var file = document.querySelector('input[type=file]').files[0]; //sames as here
var reader = new FileReader();
reader.onloadend = function () {
preview.src = reader.result;
}
if (file) {
reader.readAsDataURL(file); //reads the data as a URL
} else {
preview.src = "";
}
}
previewFile(); //calls the function named previewFile()
</script>
Summary: upload image, store it(local storage), then grab it's absolute URL to paste it on another website to get the preview of that image.

Part 1: Upload
Uploading files to PHP is easy. To give the option for an user, you must add a file input to the HTML form. Here's an example:
<input type="file" name="picture" />
To make sure PHP receives the file, you must set the form method to POST and enctype to multipart/form-data
<form action="receiver.php" method="POST" enctype="multipart/form-data">
If you want to upload through javascript you might want to use AJAX. Here's an post for an example:
https://stackoverflow.com/a/6960586/3797667
Part 2: Receive (receiver.php)
The uploaded file can be accessed through $_FILES[].
Here's an example:
if(isset($_FILES['image'])){//Checks if file is set
$errors= array();
$file_name = $_FILES['image']['name'];
$file_size =$_FILES['image']['size'];
$file_tmp =$_FILES['image']['tmp_name'];
$file_type=$_FILES['image']['type'];
$file_ext=strtolower(end(explode('.',$_FILES['image']['name'])));
//(above) checks file extension by getting text after last dot
$expensions= array("jpeg","jpg","png");//supported file types
if(in_array($file_ext,$expensions)=== false){//is the extension in the supported types
$errors[]="extension not allowed, please choose a JPEG or PNG file.";
}
if($file_size > 2097152){//PHP only supports files under 2MB
$errors[]='File size must be excately 2 MB';
}
//If there's no error moves files to folder "images" in the root of this file, else prints all the errors
if(empty($errors)==true){
move_uploaded_file($file_tmp,"images/".$file_name);
echo "Success";
}else{
print_r($errors);
}
}
For more methods on file management, check this link:
http://php.net/manual/en/ref.filesystem.php
Part 3: Access
You might want to check this post if you want to get an URL for your file:
PHP Dynamically get complete Absolute URL Path for specific file that will be included in other files
If you feel like you need more info, please comment below and I'll update the post. Good luck for your project!
Sources:
http://www.tutorialspoint.com/php/php_file_uploading.htm

Related

How to send a file from localhost to website

I want to send a preselected file (/tmp/test.txt) to a website (upload site) and get the response (shows a link to the uploaded file).
I have googled so much and didnt get it to work.
the following easy html form is working.
<html>
<body>
<form action="http://upload-site/upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="testfile" value="select file" >
<input type="submit" value="Submit">
</form>
</body>
</html>
so i all need to send is the enctype und the file with info "testfile=test.txt" i guess ??
the form ofc wants me to select a file...what i dont want.
it has to be preselected since i want to automate the upload procedure and work with the response that gives me the link to the file.
how do i do that in php/curl/js ?
You have to use different approach to send your file to another website. You're transferring file over the server(technically over two machine). You could do it by FTP. Fortunately, PHP provides you functionality for this.
<?php
$file = 'somefile.txt'; // Path of the file on your local server. should be ABSPATH
$remote_file = 'somefile.txt'; // Path of the server where you want to upload file should be ABSPATH.
// set up basic connection
$conn_id = ftp_connect($ftp_server); // $ftp_server can be name of website or host or ip of the website.
// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
// upload a file
if (ftp_put($conn_id, $remote_file, $file, FTP_ASCII)) {
echo "successfully uploaded $file\n";
} else {
echo "There was a problem while uploading $file\n";
}
// close the connection
ftp_close($conn_id);
?>
I've never tried from localhost to website (Server). Give it try and let me know your feedback for this.
Without seeing your upload.php its hard to help you, but if you want to copy the selected uploaded file to a destination on your server and then display it in the browser you need to do something like this in the file upload.php which is your forms action.
//Get the file name
$file_name = $_FILES["testfile"]["name"];
//Create destination path
$dest = "/path/to/where/you/want/the/file/" . $file_name;
//Move the file
move_uploaded_file($_FILES["testfile"]["tmp_name"], $dest)
//View the file
echo "<script> location.href='http://someip/$dest'; </script>";
I think you need to change this
<input type="file" name="testfile" value="select file">
To this
<input type="file" name="testfile" id="testfile" value="select file">
You will notice im using JavaScript to redirect the browser to the newly uploaded file, you can also just send a new HTTP header using native PHP.
header("Location: http://example.com/thefile.txt") or die("Failed!");
You can read about what you think is the best approach for the redirect here.
I hope this helps?

Dropzone js and Verot's upload, how to upload to dynamic folder?

I'm using Dropzone.js and Verot's class.upload.php to create a simple upload file.
I want to have images upload to folders dynamically from a $_GET[] variable.
Below is the code I have, but no matter what I do, all files get uploaded to "uploads" folder.
upload.php
<?php include('includes/php/class.upload.php'); ?>
<form action="upload.php" class="dropzone"></form>
<?php
$ds = DIRECTORY_SEPARATOR;
$filesFolder = 'uploads';
if(isset($_GET['album'])){
$targetDir = dirname(__FILE__).$ds.$filesFolder.$ds.$_GET['album'];
}else{
$targetDir = dirname(__FILE__).$ds.$filesFolder;
}
if(!empty($_FILES)){
$handle = new upload($_FILES['file']);
if ($handle->uploaded) {
$handle->image_resize = true;
$handle->image_x = 960;
$handle->image_ratio_y = true;
$handle->process($targetDir);
}
}
?>`
So, if the url is index.php?album=rocks, images should get uploaded to "uploads/rocks". But, right now all gets uploaded to "uploads".
If I change the $filesFolder variable directly to "uploads/rocks" file uploads to the intended folder.
Am I doing something wrong? or is there a better way to achieve this besides using $_GET.
The issue with your code is the $_GET['album'] does not exist based on your current code, So the extended path never gets created. You must use a hidden input in your form for a GET request. But also be advised if your plan on using this code in on a live website or software please properly secure the data with validation and sanitization.
<form action = "upload.php" method="get" enctype="multipart/form-data">
<input type="hidden" name="dir" value="album"/>
<input type="submit"/>
</form>

How to show the image uploaded using HTML file control on a new page after form submission in PHP?

I've a form which contains following file upload control and image control:
<form action="rebate_preview.php" role="form" method="post" enctype="multipart/form-data">
<input type="hidden" name="hidden_path" id="hidden_path" value="">
<input type="file" name="rebate_image" id="rebate_image">
<img id="rebate_old_image" src="#" alt="your image" width="80" height="80"/>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
Here I'm enabling the user to see the preview of the image he selected for upload without actually uploading the image to server using following jQuery code :
$(document).ready(function() {
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#rebate_old_image').attr('src', e.target.result);
$('#hidden_path').val(e.target.result)
}
reader.readAsDataURL(input.files[0]);
}
}
$("#rebate_image").change(function(){
readURL(this);
});
});
Now the problems I'm facing is I'm not able to show the same image preview on the next page i.e. on a file "rebate_preview.php" after form submission using image control. The next issue I'm facing is how should I store the values from array $_FILES on the page rebate_preview.php?
Remember still the image uploaded by user is not yet uploaded to the server.
The page rebate_preview.php is just a preview page with some other fields to preview the details.
How should I show this image on the page rebate_preview.php using image control and how should I store the $_FILES array data?
I had this problem a short while back when I was building an application, the best thing to create an OBJECT URL from the selected image when you select the file, you can then set your img src to that OBJECT URL data, which will render it to the page, for example lets say you have a file input with the id image_file. you could do this:
// Preview the image on the page
$('#image_file').change(function(e) {
var selected_file = $('#image_file').get(0).files[0];
selected_file = window.URL.createObjectURL(selected_file);
$('#preview_image').attr('src' , selected_file);
});
The source is now the BLOB representation of the image, you can then submit your form to upload the image or select another image to update the preview, hope this helps :)
Simple Solution?
in PHP script just do:
print "<img src='".$_POST['hidden_path']."'>";

image preview on change does not work

I have been searching for 2 days on "how to preview an image before upload". I see online live demo and copy past all code as it was. I rename my class name to match the additional js code. My code is:
$('#edit-image-upload-wrapper').prepend('<div id="imagePreview"></div>');
$(function() {
$("#edit-image-upload-wrapper").bind("change", function()
{
// alert("it works");
var files = !!this.files ? this.files : [];
if (!files.length || !window.FileReader) alert("no file selected");//return; // no file selected, or no FileReader support
if (/^image/.test( files[0].type)){ // only image file
var reader = new FileReader(); // instance of the FileReader
reader.readAsDataURL(files[0]); // read the local file
reader.onloadend = function(){ // set image data as background of div
$("#imagePreview").css("background-image", "url("+this.result+")");
}
}
});
});
I inspect my html dom and see the following code :
<div class="form-item" id="edit-image-upload-wrapper"><div id="imagePreview"></div>
<label for="edit-image-upload">Upload Your Picture: <span class="form-required" title="This field is required.">*</span></label>
<input type="file" name="files[image_upload]" class="form-file required" id="edit-image-upload" size="60">
<div class="description"><p>You need to provide a passport sized image in jpg/jpeg or png format. The image size has to be 100kb or lower.</p>
</div>
</div>
Which is exactly same as this demo: http://www.phpgang.com/how-to-show-image-thumbnail-before-upload-with-jquery_573.html
But when I change the image , alert("no file selected"); works that proves no file selected. What am I doing wrong. please help.
Check my previews answer is work fine show image before upload
Show an image preview before upload

Possible to send an image file to PHP with AJAX?

I'm trying to send an image file along with other text information using AJAX, however I can't get the file part to work, as I don't quite understand how to do it.
Here is the Javascript:
//The user selects a file using an input element with the ID "picInput"
var picInput = document.getElementById("picInput");
picValue = picInput.files[0];
//"postString" is the string with all the other text information that is being sent
//All the other info in it is received fine, it is just the picture having problems
postString += "pic=" + picValue;
var xmlhttp = new XMLHttpRequest;
xmlhttp.open("POST","handler.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(postString);
And here is the PHP:
$pic = $_FILES['pic'];
ftp_put($ftpCon,"pics/".$name,$pic,FTP_BINARY) or die(mysqli_error($con));
With this code, I get 'undefined index' for the "$pic = $_FILES['pic'];" line.
If I change $_FILES to $_POST I get "ftp_put([object File]): failed to open stream: No such file or directory"
Are you trying to ajax a form content? If yes you could try AJAX form Plugin
$("body").on('submit','form#someForm', function(e){
e.preventDefault();
$(this).ajaxSubmit({
target: '#output',
success: afterSuccess
});
});
Then you'll have to put the file and the rest of your contents in
<form id="someForm" method="post" action="handler.php"></form>
and name your file input like
<input type="file" name="pic" />
the afterSuccess function will be called after everything is done
the #output can be used to show progress or things like that

Categories

Resources