I need a code that can instant upload an image from the pc to my website after I select it without needet to click submit or to refresh the page. This is the code that I have until now!
<img id="uploadPreviewprofile" style="max-width: 990px; max-height: 320px;text-align:center; position:absolute;" />
<div class="fileUploadprofile btn btn-primary" style="position:absolute; margin-top:298px;">
<form method="post" enctype="multipart/form-data">
<input id="uploadImageprofile" type="file" name="fotoprofile" class="uploadprofile" onchange="PreviewImageprofile();" />
</div>
<script type="text/javascript">
function PreviewImageprofile() {
var oFReader = new FileReader();
oFReader.readAsDataURL(document.getElementById("uploadImageprofile").files[0]);
oFReader.onload = function (oFREvent) {
document.getElementById("uploadPreviewprofile").src = oFREvent.target.result;
};
};
</script>
</div>
Just ajax it over to your server after you read the file, e.g.:
HTML
<input id="instant" type="file">
JavaScript
// Note: I am using jQuery here, so you need to include the library
$("#instant").on("change", function() {
$.each(this.files, function(index, file) {
// read file data
reader = new FileReader();
reader.onload = function(event) {
// send to server
$.post("upload.php", {name: file.name, image: event.target.result});
}
reader.readAsDataURL(file);
});
});
PHP
<?php
if($_POST["image"]) {
// image is base64 encoded, so let's unparse it
$parts = explode(",", $_POST["image"]);
// check that we have the image
if(isset($parts[1])) {
// save the image
file_put_contents($_POST["name"], base64_decode($parts[1]));
}
}
And that's all the magic..
Quick recap:
1) We select the image via standard file upload tag
2) We capture the change the push the base64 encoded image to the server using an AJAX Post
3) We parse the base64 encoded image (which is in the Data URI scheme) and decode the base64 data part of it. This will give us the binary data from the actual image/file to save to the hard drive using the original name of it.
Now this code doesn't have any checks, etc. But it gives you the core functionality to continue your work.
Related
Here is my code. i want to upload the image file using ajax, php. when the image file is uploaded it should show the preview. The image file is successfully uploading but the ajax success is not showing the preview.
Here is my form code:
<form method="post" enctype="multipart/form-data">
<div class='preview'>
<img src="" id="photo_disp" width="100" height="100">
</div>
<input type="file" name="file1" id="file1" accept=".jpeg,.jpg" required/>
<button type="submit" id="btn_photo" name="submit">Upload Photo</button>
</form>
Here is the ajax i have used. The ajax is successfully posting the file to php code but the success response is not working.
<script>
$(document).on('click','#btn_photo',function(){
var fd = new FormData();
var files = $('#file1')[0].files;
// Check file selected or not
if(files.length > 0 )
{
fd.append('file',files[0]);
$.ajax({
url:'ajax_photo.php',
type:'post',
data:fd,
contentType: false,
processData: false,
success:function(response)
{
alert(response);
if(response != 0)
{
$("#photo_disp").attr("src",response);
}
else
{
alert('File not uploaded');
}
}
});
}
else
{
alert("Please select a file.");
}
});
</script>
Here is my php code using on click
<?php
if(isset($_FILES['file']['name']))
{
session_start();
$filename = $_FILES['file']['name'];
$roll=$_SESSION['name'];
$imageFileType = pathinfo($filename,PATHINFO_EXTENSION);
$imageFileType = strtolower($imageFileType);
$valid_extensions = array("jpg","jpeg");
$response = 0;
if(in_array(strtolower($imageFileType), $valid_extensions))
{
$location = "upload/".$roll.".".$imageFileType;
if(move_uploaded_file($_FILES['file']['tmp_name'],$location))
{
$response = $location;
}
}
echo $response;
exit;
}
echo 0;
?>
Please find out where i did the mistake. The image is successfully uploading to the given path but the image is not showing in the preview. i have written an alter in the success. But the alert is also not working.
If the response refers to a fully qualified resource path (https:example.com/upload/cat-dancing.jpg) on the server, you can assign it directly to the image's src attribute just like you've done in your question.
$("#photo_disp").attr("src",response);
If the returned resource path doesn't contain the domain name (upload/cat-dancing.jpg), prepend it with a forward slash to indicate that the path starts from the document root of the website. I.e:
$("#photo_disp").attr("src", "/" + response);
Otherwise, if the response is an actual File or Blob, you could set the image's src attribute using:
const img = $("#photo_disp").get(0);
img.src = URL.createObjectURL(response);
img.height = 60;
img.onload = function() {
URL.revokeObjectURL(this.src);
}
Set the image's source to a new object URL representing the file, using
URL.createObjectURL()
to create the blob URL.
Set the image's height to 60 pixels.
Set up the image's load event handler to release the object URL since it's no longer needed once the image has been loaded. This is
done by calling the
URL.revokeObjectURL()
method and passing in the object URL string as specified by img.src.
Resource:
Example: Using object URLs to display images
I'm trying to upload a photo by using ajax.
My input:
<input type="file" name="defaultPhoto">
A part of my jQuery code.
var form = #insertCredentials
var defaultPhoto = $('#' + form + ' ' + '[name = "defaultPhoto"]').prop('files');
I'm sending defaultPhoto through an ajax call to my php alongside with other form inputs.
The console gives back this error below:
TypeError: 'slice' called on an object that does not implement interface Blob.
I have implemented the AJAX way of file uploading using Dropzone JS.
It will really make your life simple
Check the Dropzone.js Website
All you need to do is instantiate the dropzonejs object and set the options
Dropzone.options.myAwesomeDropzone = {
paramName: "file", // The name that will be used to transfer the file
maxFilesize: 2, // MB
accept: function(file, done) {
if (file.name == "image.jpg") {
done("Naha, you don't.");
}
else { done(); }
}
};
you can't send file via ajax
try to use hidden iframe in form target with normal submit
<form name="" action="/your_iframe_action_url" taget="hidden_iframe_name">
<input type="file" />
<input type="submit" />
</form>
<iframe name="hidden_iframe_name" style="width:0; height:0" />
In your_iframe_action_url you can call javascript parent functions to execute event success or failure... that simulate underground upload
you can use document.getElementById('whatever').files;
to get the file
and then use
formdata
to send the files via ajax.
here is the example
you can also use File reader to show file on loaded
here is the example for filereader
My requirement is to save the images taken from Camera of Cordova plugin and save the image in a server . I have used below code and achieved getting the image , but how do i save in a server using PHP
// Code to capture photo from camera and show gps co ordinates
<!DOCTYPE html>
<html>
<head>
<title>Capture Photo</title>
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script type="text/javascript" charset="utf-8">
var pictureSource; // picture source
var destinationType; // sets the format of returned value
// Wait for device API libraries to load
document.addEventListener("deviceready",onDeviceReady,false);
// device APIs are available
function onDeviceReady() {
pictureSource=navigator.camera.PictureSourceType;
destinationType=navigator.camera.DestinationType;
}
// Called when a photo is successfully retrieved
//
function onPhotoDataSuccess(imageData) {
// Uncomment to view the base64-encoded image data
// console.log(imageData);
// Get image handle
//
var smallImage = document.getElementById('smallImage');
// Unhide image elements
//
smallImage.style.display = 'block';
// Show the captured photo
// The in-line CSS rules are used to resize the image
//
smallImage.src = "data:image/jpeg;base64," + imageData;
}
// Called when a photo is successfully retrieved
//
function onPhotoURISuccess(imageURI) {
// Uncomment to view the image file URI
// console.log(imageURI);
// Get image handle
//
var largeImage = document.getElementById('largeImage');
// Unhide image elements
//
largeImage.style.display = 'block';
// Show the captured photo
// The in-line CSS rules are used to resize the image
//
largeImage.src = imageURI;
}
// A button will call this function
//
function capturePhoto() {
// Take picture using device camera and retrieve image as base64-encoded string
navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 50,
destinationType: destinationType.DATA_URL });
}
// A button will call this function
//
function capturePhotoEdit() {
// Take picture using device camera, allow edit, and retrieve image as base64-encoded string
navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 20, allowEdit: true,
destinationType: destinationType.DATA_URL });
}
// A button will call this function
//
function getPhoto(source) {
// Retrieve image file location from specified source
navigator.camera.getPicture(onPhotoURISuccess, onFail, { quality: 50,
destinationType: destinationType.FILE_URI,
sourceType: source });
}
// Called if something bad happens.
//
function onFail(message) {
alert('Failed because: ' + message);
}
</script>
</head>
<body>
// button to capture photo
<button onclick="capturePhoto();">Capture Photo</button> <br>
// button to capture editable photo
<button onclick="capturePhotoEdit();">Capture Editable Photo</button> <br>
//button to select images from library
<button onclick="getPhoto(pictureSource.PHOTOLIBRARY);">From Photo Library</button><br>
<button onclick="getPhoto(pictureSource.SAVEDPHOTOALBUM);">From Photo Album</button><br>
<img style="display:none;width:60px;height:60px;" id="smallImage" src="" />
<img style="display:none;" id="largeImage" src="" />
</body>
</html>
PHP Code (upload.php):
<?php
print_r($_FILES);
move_uploaded_file($_FILES["file"]["tmp_name"], "192.168.3.153/uploads/".$_FILES["file"]["name"]);
?>
The only way to do this is to get the image as a Base64 encoded string, send that back to the server and then save it into the DB, either in encoded form, or decode it and then save it as a file on the server or a blob in a database.
I don't know the exact implementation procedure as I'm not a Cordova dev, I just sit next to one at work who was tearing his hair out over something similar recently.
In cordova we have plugin file transfer which is used to download / upload files from server. You have to use this plugin to upload image taken from camera.
Check following link that details how to upload file to server
Following is a Javascript function that picks a file stored in mobile device and send it to server
function uploadfiletoserver(filename){ // where filename is the file store in device
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSys) {
//The folder is created if doesn't exist
fileSys.root.getDirectory( 'APP STORAGE FOLDER', {create:true, exclusive: false},
function(directory) {
//find the file
directory.getFile(filename, {create: false, exclusive: false},
function(file){
var imageURI = file.toInternalURL();
var options = new FileUploadOptions();
options.fileKey = "uploadfile"; //this is the value use to refer the file uploaded to server e.g. $_FILES['uploadfile']
options.fileName = file.name;
var ft = new FileTransfer();
ft.upload(imageURI, encodeURI('http://www.yourdomain.com/upload.php'), function (r) {
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
console.log("Sent = " + r.bytesSent);
}, function (error) {
console.log("upload error source " + error.source);
console.log("upload error target " + error.target);
}, options);
console.log("upload file: "+imageURI);
},
function(error){
console.log("Error "+error);
}
);
},
resOnError);
},
resOnError);
}
In server PHP file,
<?php
$tmpName = $_FILES['uploadfile']['tmp_name'];
$fileName = $_FILES['uploadfile']['name'];
$fileDestPath = 'YOUR_UPLOAD_FOLDER_IN_SERVER'.$fileName;
if($tmpName != 'none') {
move_uploaded_file($tmpName, $fileDestPath);
}
?>
I want to upload file using ajax but i dont get data in php $_FILES and I get it in $_REQUEST. How do I do it. Below is my jquery code.Ajax is not working for file uploading so is there any code so that i can merge with existing code for file uploading process.
<script>
jQuery(function($){
jQuery('#btn').click(function(){
var data = {},
ticks = [];
$('.ajax_elements').each(function(_, elem) {
data[this.id] = this.value;
});
$.ajax({
type : 'POST',
url : 'app_process.php',
data : data,
cache : false
}).done(function(result) {
alert(result);
});
});
});
</script>
<form name="frm" enctype="multipart/form-data">
<input type="text" name="bb" class="ajax_elements" id="one"/>
<input type="file" class="ajax_elements" name="passport" id="passport" />
<input type="button" name="bttn" id="btn" />
</form>
here is php file code
<?php
if($_REQUEST['passport']!=''):
$uploaddir = 'images/';
move_uploaded_file($_FILES["file"]["tmp_name"], $uploaddir . str_replace(" ","_",$_REQUEST['passport']));
endif;
?>
error message
Notice: Undefined index: file in
G:\xampp\htdocs\data_ajax\app_process.php on line 5
My advice would be to look at the XMLHttpRequest, FormData and File APIs. The Mozilla Developer Network have great documentation on all of these.
This needs testing and tweaking to be more robust in your development environment, but something along the lines of this could get you started...
<script>
$('#btn').click(function() {
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener("load", function(e){
// stuff to do when upload is complete
}, false);
xhr.upload.addEventListener("progress", function(e){
// stuff here to handle progress bars, progress percentages etc.
}, false);
xhr.open('POST', 'app_process.php', true);
var formdata = new FormData();
var file = $('#passport').get(0).files[0];
formdata.append('passport', file);
xhr.send(formdata);
});
</script>
And the PHP...
<?php
if (isset($_FILES['passport'])) {
$uploaddir = 'images/';
$upload = move_uploaded_file($_FILES['passport']['tmp_name'], $uploaddir . str_replace(" ","_",$_FILES['passport']['name'])) or exit('Upload failed.');
} else {
exit('File not found');
}
?>
Any additional information you want to send with the file needs to be added to the FormData object. These will appear in the PHP $_POST variable.
formdata.append('field', 'data');
Bear in mind that these APIs are not universally supported in browsers, so best practice is to include all the usual feature detection scripts before the user reaches this point.
You could also bind the upload function to the change event of the file input instead of asking for a button click...
$('#passport').change(function() { ...
Hope that helps.
There is 2 problems :
You need to add the attribute enctype="multipart/form-data" in the form tag if you want to upload files:
replace
<form name="frm">
by
<form name="frm" enctype="multipart/form-data" >
With ajax (and jquery), you cannot send file directly. But I suggest you that jquery form plugin who can help you with that
I am dealing with a form that contains various form elements with an option to upload multiple images(upto 6 max). Now i am having a div preview on clicking that div i fetch all form fields using jquery (form still not submitted at this time as its a multi form step1, 2 and 3). Now the problem is that i am fetching all form data with this code -
var allFormData = $("#myform").serializeArray();
Using this another code i am able to show rest of the data in div, but image is not coming.
$.each(adtitletoshow, function(i, field){
if( field.name == 'desc'){
$(".add_desc").text(field.value);
}
});
This is the filed created by JS to upload image.
<script type="text/javascript">
var total_images = 1 ;
function add_file_field () {
total_images++ ;
if ( total_images > 6 ) return ;
var str_to_embed = '<input name="fileImage[]" size="40" style="width: 500px;" type="file" onChange="add_file_field()"><br>' ;
$("#image_stack").append ( str_to_embed ) ;
}
</script>
All things going on single page so i need a solution that how can i load images under my preview div. Let me know if thr is some point of ambiguity still persists.
You need to loop through the files array from the multiple input and use the FileReader API on each.
I've set up the HTML like this:
<input type="file" multiple="true" id="files" />
<input type="submit" id="go"/>
<div id="images"></div>
Then the javascript as follows:
// set up variables
var reader = new FileReader(),
i=0,
numFiles = 0,
imageFiles;
// use the FileReader to read image i
function readFile() {
reader.readAsDataURL(imageFiles[i])
}
// define function to be run when the File
// reader has finished reading the file
reader.onloadend = function(e) {
// make an image and append it to the div
var image = $('<img>').attr('src', e.target.result);
$(image).appendTo('#images');
// if there are more files run the file reader again
if (i < numFiles) {
i++;
readFile();
}
};
$('#go').click(function() {
imageFiles = document.getElementById('files').files
// get the number of files
numFiles = imageFiles.length;
readFile();
});
I've set up a JSFiddle to demo http://jsfiddle.net/3LB72/
You'll probably want to do more checks on whether the browser the user is using has FileReader and if the files they have chosen are image files.
JSFiddle demo
This is much better, without clicking any button :D
HTML:
<input type="file" multiple="true" id="files" />
<input type="submit" id="go"/>
<div id="images"></div>
JavaScript:
// set up variables
var reader = new FileReader(),
i=0,
numFiles = 0,
imageFiles;
// use the FileReader to read image i
function readFile() {
reader.readAsDataURL(imageFiles[i])
}
// define function to be run when the File
// reader has finished reading the file
reader.onloadend = function(e) {
// make an image and append it to the div
$("#images").css({'background-image':'url('+e.target.result+')'});
// if there are more files run the file reader again
if (i < numFiles) {
i++;
readFile();
}
};
$('#files').live('change', function(){
imageFiles = document.getElementById('files').files
// get the number of files
numFiles = imageFiles.length;
readFile();
});