I have a site where I would like to upload a profile picture to the server and store the image into the database, using ajax. This is pretty straight forward and does work. But I would like to be able to get the user to be able to to crop their image so that it is square using Jcrop. I have seen and downloaded examples of how to implement Jcrop, which are pretty straight foreword. But I just can't seen to get it to work on my site. The code I have so far is rough and still needs a bit of validation but I want to get the main function dealt with first.
To make the cropping process seem a little more user friendly I have created a basic light-box type thing to hold the upload form and then the image to crop after sent back from php. This seems to be the only difference form what I've seen online.
Here's my code:(I have just picked out the relevant parts as the site contains quite a lot of text and images in other divs that aren't relevant)
HTML IMPORTS:
<script src="jquery/jquery.min.js"></script>
<script src="jquery/jquery.Jcrop.min.js"></script>
<link rel="stylesheet" href="css/jquery.Jcrop.css" type="text/css" />
HTML: - form to upload a new Profile Pic
<div id="reg_pp">
<img src="images/logo.png" width="100%" height="150px" /><br/><button id="updateGender" style="float:right; width:auto;" class="form_fields_button" onclick="changeProfilePic('open')">Change Profile Picture</button>
</div>
HTML: - lightbox type thing
<div id="ppuo" class="overlay">
<div id="ppufh" class="tcs">
<div id="close_btn" onclick="changeProfilePic('close')"></div>
<div id="nppf">
<div id="preview"><img src="assests/preview.png" width="150px" height="150px" id="thumb" /></div>
<form id="uploadPP" enctype="multipart/form-data">
<input id="image" name="image" type="file" class="form_fields" size="20" style="width:100%" />
<input type="hidden" id="user" name="user" value="session_generated_id"/>
<div id="npp_err_msg"></div>
<input type="button" id="changePPBtn" value="preview" onclick="check()" />
</form>
</div>
</div>
</div>
Javascript: -toggle profile picture change dialog/lightbox
function changeProfilePic(toggle){
var overlay = document.getElementById('ppuo');
var content = document.getElementById('ppufh');
if(toggle === 'open'){
//display overlay
$('#ppuo').fadeIn({complete:function(){}},500);
}else{
//hide display
$('#ppuo').fadeOut({complete:function(){}},500);
}
}
JavaScript: - upload image and start of JCrop
function check(){
var formData = new FormData($('#uploadPP')[0]);
$.ajax({
url: 'global.func/upLoadPP.php',
type: 'POST',
xhr: function(){
var myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){
//myXhr.upload.addEventListener('progress',progressHandlingFunction, false); // For handling the progress of the upload
}
return myXhr;
},
data: formData,
//Ajax events
//beforeSend: beforeSendHandler,
success: function(data){
var return_type = data.substr(0,1);
var data_type = data.split(":");
if(parseInt(data_type[0]) === 4 || data_type[0] === '4'){
//no error
$('#ppufh').animate({width:'800px',height:'80%',marginTop:'10%'},500);
document.getElementById('thumb').src = data_type[1];
document.getElementById('thumb').style.width = '80%';
document.getElementById('thumb').style.height = 'auto';
document.getElementById('ppufh').style.overflow = 'scroll';
$('#thumb').JCrop({
aspectRatio: 1,
onChange: updateCoords,
onSelect: updateCoords,
bgColor: 'blue',
bgOpacity: .5,
sideHandles:false,
minSize: [ 50, 50 ]
});
document.getElementById('changePPBtn').value = 'Finished Cropping';
$('#changePPBtn').on('click',function(){
window.alert("save new profile pic");
});
}else{
var err_msg = data_type[1];
document.getElementById('npp_err_msg').innerHTML = '<h3 style="text-align:left">'+data+'</h2>';
}
},
error: function(){
alert("There has been an internal server error. Please try again.");
},
cache: false,
contentType: false,
processData: false
});
}
PHP: -in case it helps but does work fine as a basic start
<?php
include '../constant/connect.php';
$row_count = mysql_num_rows(mysql_query("SELECT * FROM profile_pics"));
if(isset($_POST)){
$user_email = $_POST['user'];
$file = $_FILES['image'];
if($_FILES['image']['error'] > 0){
echo '0:php server error adjust php.ini file, then change this error message.';
}else{
$file_type = $_FILES['image']['type'];
$file_name = $_FILES['image']['name'];
$extention = explode('.',$file_name);
$extention = $extention[1];
if($extention == 'jpeg' || $extention == 'png' || $extention == 'gif'){
$path = '../images/user_profile_pictures';
$new_file_name = md5($file_name.$row_count).".".$extention;
move_uploaded_file($_FILES["image"]["tmp_name"], "../images/user_profile_pictures/" . $new_file_name);
$query = mysql_query("INSERT INTO profile_pics (pp_src,pp_owner) VALUES ('".$path."/".$new_file_name."','$user_email')")or die(mysql_error());
echo '4:images/user_profile_pictures/'.$new_file_name;
}else{
echo '1:Wrong type of file, use jpg, jpeg, png or gif. No animated Gifs.';
}
}
}else{
echo 'data not passed';
}
?>
It looks like it should work but there may be something I have missed and can't spot that somebody else can. So if anybody can help it would be greatly appreciated.
getElementById('thumb').style.height = 'auto';
document.getElementById('ppufh').style.overflow = 'scroll';
$('#thumb').JCrop({
aspectRatio: 1,
onChange: updateCoords,
onSelect: updateCoords,
bgColor: 'blue',
bgOpacity: .5,
sideHandles:false,
minSize: [ 50, 50 ]
});
document.getElementById('changePPBtn').value = 'Finished Cropping';
$('#changePPBtn').on('click',function(){
window.alert("save new profile pic");
});
}else{
var err_msg = data_type[1];
document.getElementById('npp_err_msg').innerHTML = '<h3 style="text-align:left">'+data+'</h2>';
}
},
error: function(){
alert("There has been an internal
Related
I'm using Dropzone.js,I displayed server images inside dropzone box with remove link and it works fine but my problem is when I click on butto to save uploaded images server images not saving in database just new uploaded images are saving
my code
<script type="text/javascript">
Dropzone.options.dropzone =
{
autoProcessQueue: false,
maxFiles: 50,
maxFilesize: 12,
acceptedFiles: ".jpeg,.jpg,.png,.gif",
addRemoveLinks: true,
uploadMultiple: true,
timeout: 50000,
init: function () {
var myDropzone = this;
$.get('/getphoto',{'key': $('[name=key]').val()},function(data){
var files = data;
console.log(files.length);
for (var i = 0; i < files.length; i++) {
var name= files[i].name;
var link = "http://127.0.0.1:8000/storage/images/events/galleries/"+ name;
console.log(link);
var mockFile = { name: files[i].name, size: 128456, type: 'image/png', url:link};
myDropzone.emit('addedfile', mockFile);
myDropzone.options.thumbnail.call(myDropzone, mockFile, link);
myDropzone.emit('complete', mockFile);
myDropzone.files.push(mockFile);
var existingFileCount = 1; // The number of files already uploaded
myDropzone.options.maxFiles = myDropzone.options.maxFiles - existingFileCount;
}
});
// Update selector to match your button
$("#button").click(function (e) {
e.preventDefault();
myDropzone.processQueue();
});
this.on('sending', function(file, xhr, formData) {
// Append all form inputs to the formData Dropzone will POST
var data = $('#dropzone').serializeArray();
$.each(data, function(key, el) {
formData.append(el.name, el.value);
});
});
},
removedfile: function(file)
{
var fileRef;
return (fileRef = file.previewElement) != null ?
fileRef.parentNode.removeChild(file.previewElement) : myDropzone.removeFile(file);
},
success: function(file, response)
{
var name = file.upload.filename;
console.log(name);
window.location.href = "{{ route('eventlist') }}";
},
error: function(file, response)
{
return false;
}
};
function del(file)
{
console.log(file.name);
return myDropzone.removeFile(file);
}
</script>
my view blade:
<div>
<form action="{{ route('savegallery',$event->id) }}" class="dropzone" id="dropzone" method="POST" class="dropzone" enctype="multipart/form-data">
#csrf
{{-- <div class="fallback">
<input name="images" type="file" multiple="multiple">
</div> --}}
<div class="dz-message needsclick">
<div class="mb-3">
<i class="display-4 text-muted mdi mdi-upload-network-outline"></i>
</div>
<h4>Drop files here or click to upload.</h4>
</div>
</form>
</div>
<div class="text-center mt-4">
<button type="submit" id="button" class="btn btn-primary waves-effect waves-light">Send
Files</button>
</div>
First I delete all images then I get images from dropzone then save it
public function savegallery(Request $request,$id){
$eventgalleries = Eventgallery::where('event_id',$id)->delete();
foreach ($request->file('file') as $img) {
// $image = new Eventgallery;
//get file name with extention
$filenameWithExt = $img->getClientOriginalName();
//get just file name
$filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
//GET EXTENTION
$extention = $img->getClientOriginalExtension();
//file name to store
$fileNameToStore = $filename . '_' . time() . '.' . $extention;
//upload image
$path = $img->storeAs('public/images/events/galleries', $fileNameToStore);
$url = asset('storage/images/events/galleries/' . $fileNameToStore);
$img = new Eventgallery;
$img->name = $fileNameToStore;
$img->event_id = $id;
$img->save();
}
return redirect()->route('eventlist')->with('success', 'The galleries created successfully.');
}
and this function for route (/getphoto) to get all images and then display it in dropzone
public function getphoto(){
$data = Eventgallery::all()->toArray();
return $data;
}
Can someone help me I spend many days to find a solve but no result.
I am trying to load an changed image into a modal box with ajax. For example, the photo changes to the selected one when I click "Make Profile Picture" but it keeps the old one showing in the modal box unless I refresh the page. Is there a way to have ajax execute not just on page load but perhaps execute always to check the photo is the new one?
Here is the code I have in place:
PHP -
public function getprofileimageAction()
{
$layout = $this->layout();
$layout->setTerminal(true);
$view_model = new ViewModel();
$view_model->setTerminal(true);
$params = $this->identity();
$dir = #array_diff(#scandir(getcwd() . '/public/images/profile/' . $params . '/current/', 1), array('.', '..'));
if (!$dir) {
// set default avatar
$string_img = "<img src=\"/images/profile/defaults/avatar2.png\" class=\"w3-round w3-border\" onclick=\"document.getElementById('a-modal').style.display='block'\"
style=\"width: 200px; height: 200px;\" alt=\"Avatar\" id=\"avatar\">";
} else {
$string_img = "<img src=\"/images/profile/$params/current/$dir[0]\" class=\"w3-round w3-border\" onclick=\"document.getElementById('a-modal').style.display='block'\"
style=\"width: 200px; height: 200px;\" alt=\"Avatar\" id=\"avatar\">";
}
$data = array(
'profile_photo' => $string_img
);
echo $data['profile_photo'];
return $view_model;
}
JavaScript/jQuery -
var replaced_src;
var replace;
$.ajax({
type: "POST",
url: "/members/profile/get-profile-image",
}).done(function(data) {
$("#profile-pic").html(data);
replaced_src = $("#avatar").attr('src');
replace = replaced_src.replace(/(defaults)/g, '');
// fix this so it loads the changed image.
$('#current-photo').html("<img src='" + replace + "' alt='Avatar' class='w3-center w3-round w3-border' style='height: 280px; width: 400px;'>");
}).fail(function(data) {
alert("Error loading image");
});
This is the event click to change the profile picture
$('#make-profile-photo').on('click', function() {
$.ajax({
type: "POST",
url: "/members/profile/change-profile-picture",
data: { image: $('#other-photo').attr('src') }
}).done(function() {
document.getElementById('p-modal').style.display = 'none';
$('#profile-pic').load('/members/profile/get-profile-image');
});
});
HTML -
<div class="w3-modal" id="a-modal">
<div class="w3-modal-content w3-card-4 w3-theme-d2 w3-round" style="width: 432px;">
<div class="w3-container">
<p class="w3-center w3-small">
<span onclick="document.getElementById('a-modal').style.display = 'none'" class="w3-closebtn">×</span>
Current Profile Picture
</p>
<br>
<p id="current-photo" class="w3-center">
<br>
</p>
<script type="text/javascript">
var modal = document.getElementById('a-modal');
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = 'none';
}
}
</script>
<div class="w3-clear"></div>
</div>
</div>
</div>
So basically what I am asking is if there is a way to reload the changed image so $('#current-photo') will display it without having to refresh the page.
Hope that makes sense
Thanks!
If it helps, here is a screenshot of my issue:
http://imgur.com/a/DkPhQ
Hi i am trying to upload an image with comments added to it into a database using php ajax and html.
here is the html part:
<form name="form1" enctype="multipart/form-data" action="">
<h2></h2>
<div class="form-group">
<textarea name="msg" class="form-control status-box" id="post" rows="3" cols="60" placeholder="What\'s on your mind?"></textarea>
<p>Upload an image.</p>
<input type="file" id="postPhoto" name="postPhoto" value="upload" placeholder="Upload Image">
</div>
</form>
<div class="button-group pull-right">
<p class="counter">200</p>
<a href="#" type="submit" onclick="submitChat()" class="post btn btn-primary">
Post</a>
</div><br><br>
this is what i have to the ajax which is on the same page as the html
<script>
function submitChat() {
var file = document.getElementById("postPhoto");
var formData = new FormData();
// alert(formData);
formData.append("file[]", file.files[0]);
if(form1.msg.value == '') {
alert('You must Enter a Post');
return;
}
var msg = form1.msg.value;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById('logs').innerHTML = xmlhttp.responseText;
console.log(xmlhttp.statusText);
}
}
xmlhttp.open('POST', 'userposts.php?msg='+msg, true);
xmlhttp.setRequestHeader("Content-type", "multipart/form-data");
xmlhttp.send(formData);
}
<script>
and this is the php part:
$msg = stripslashes(htmlspecialchars($_REQUEST['msg']));
if(isset($_FILES['postPhoto']['type'])) {
$imageData = "";
$validextensions = array("jpeg", "jpg", "png");
$temporary = explode(".", $_FILES['postPhoto']['name']);
$file_extension = end($temporary);
if((($_FILES['postPhoto']['type'] === 'image/png') || ($_FILES['postPhoto']['type'] == 'image/jpg') || ($_FILES['postPhoto']['type'] == 'image/jpeg')) && ($_FILES['postPhoto']['size'] < 2500000) && in_array($file_extension, $validextensions)) {
if($FILES['postPhoto']['error'] > 0) {
echo "return code: " . $_FILES['postPhoto']['error'] . "<br/><br/>";
}
else {
$imageData = mysqli_real_escape_string($connection, file_get_contents($_FILES["postPhoto"]["tmp_name"]));
}
}
}
$stmt = "INSERT INTO posts VALUES ('', '$uname', '$msg', '$imageData')";
$result = $connection->query($stmt);
the images do not seem to be getting sent to the php file idk how to go about fixing this. any help would be much appreciated.
Maybe Helpful,
You simply can't upload a file with pure Javascript ajax functions (at least not in a cross browser way, see this article for more information)
This is because XMLHttpRequest has no support for multipart/form-data, you can do tricks like using an iframe or use flash.
There are enough articles on the internet that explain this.(maybe helpful)
http://www.ajaxf1.com/tutorial/ajax-file-upload-tutorial.html
http://www.faqs.org/rfcs/rfc2388.html
Recomand
Use jQuery Ajax. which have easy lib. support and functions to upload images and submit/parse to destination files.
below sample jQuery AJAX code for demo
$(document).ready(function(){
$(document).on('submit','form[name="form1"]',function(e){
e.preventDefault();
var form = $(this)[0];
var formData = new FormData(form);
$.ajax({
url: 'Your url here',
data: formData,
type: 'POST',
// THIS MUST BE DONE FOR FILE UPLOADING
contentType: false,
processData: false,
// ... Other options like success and etc
success : function(data){
//Do stuff for ahed process....
}
});
});
});
I want to upload an image in onchange of the input type file using AJAX. I can only use javascript, ajax and php.
Look my code:
index.html
<form id="myForm" action="" enctype="multipart/form-data">
<input type="file" name="imagefile" id="imagefile" onchange="uploadImage()">
</form>
upoad.js
function uploadImage(){
try {
ajpass = new XMLHttpRequest();
} catch (e) {
ajpass = new ActiveXObject("Microsoft.XMLHTTP");
}
ajpass.onreadystatechange = epasscheck2;
ajpass.open("post", "http://localhost/moodle/lib/editor/tinymce/plugins/moodleimage/upload.php", true);
ajpass.send();
}
function epasscheck2() {
if ((ajpass.readyState == 4) && (ajpass.status == 200)) {
var restxt = ajpass.responseText;
alert(restxt);
}
}
upload.php
<?php
echo $_FILES["imagefile"]["name"]; //error here
//file upload code here
?>
I am getting the error Undefined index imagefile in upload.php.
I am failed to pass the image file properties(like name, size, tmp_name etc) from upload.js to upload.php.
use the coding below it will help you to validate file
$(document).ready(function (e) {
$("#form").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "upload.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
beforeSend : function()
{
//$("#preview").fadeOut();
$("#err").fadeOut();
},
success: function(data)
{
if(data=='invalid file')
{
// invalid file format.
$("#err").html("Invalid File !").fadeIn();
}
else
{
// view uploaded file.
$("#preview").html(data).fadeIn();
$("#form")[0].reset();
}
},
error: function(e)
{
$("#err").html(e).fadeIn();
}
});
}));
});
<form id="form" action="upload.php" method="post" enctype="multipart/form-data">
<input id="uploadImage" type="file" accept="image/*" name="image" />
<input id="button" type="submit" value="Upload">
</form>
<div id="err"></div>
you must create a folder "upload".
<?php
$valid_extensions = array('jpeg', 'jpg', 'png', 'gif', 'bmp'); // valid extensions
$path = 'uploads/'; // upload directory
if(isset($_FILES['image']))
{
$img = $_FILES['image']['name'];
$tmp = $_FILES['image']['tmp_name'];
// get uploaded file's extension
$ext = strtolower(pathinfo($img, PATHINFO_EXTENSION));
// can upload same image using rand function
$final_image = rand(1000,1000000).$img;
// check's valid format
if(in_array($ext, $valid_extensions))
{
$path = $path.strtolower($final_image);
if(move_uploaded_file($tmp,$path))
{
echo "uploaded";
}
}
else
{
echo 'invalid file';
}
}
?>
I feel like a necromancer right now, but regardless, it seems to me that the primary issue in this case was that no actual data was sent in the send() function. Since XMLHttpRequest is being used the form data isn't sent with it as it would be through a redirect directly through HTML. To rectify this, we'd need to first of all grab the file.
const img = document.getElementById("imagefile");
if (img.files.length == 0) return;
const file = img.files[0];
After which I suppose all there is left to do is to actually send the data.
const data = new FormData();
data.append("imagefile", file);
ajpass.send(data);
And with this, you hopefully would get a working result. Since I'm feeling generous, I'll also give you an extra PHP bit that can be useful.
if (isset($_FILES['imagefile']) {
...
}
isset() will more easily help you see if what you're looking for actually exists within the context. It makes finding where things go wrong if they do, and you can avoid nasty error messages.
You can use Dropzone instead of reinventing the wheel,
Here's the link : http://www.dropzonejs.com/#
I've been trying to find a very basic AJAX jQuery Avatar Uploading that I can use for my "settings" page so users can upload an avatar and unfortunately I can't find any.
This is my "function" so far for uploading the avatar
function uploadAvatar(){
$('#avatarDialog').fadeIn();
$('#avatarDialog').html("Logging in, please wait....");
dataString = $('#avatarForm').serialize();
var postURL = $('#avatarForm').attr("action");
$.ajax({
type: "POST",
url: site_url+"/libraries/ajax/image-upload.php",
data:dataString,
dataType:"json",
cache:false,
success:function(data){
if(data.err){
$('#avatarDialog').fadeIn();
$('#avatarDialog').html(data.err);
}else if(data.msg){
$('#avatarDialog').fadeIn();
$('#avatarDialog').html(data.msg);
var delay = 2000;
window.setTimeout(function(){
location.reload(true);
}, delay);
}
}
});
return false;
};
For my HTML/Input is this.
<form id="avatar_form" action enctype="multipart/form-data" method="post">
<input name="image_file" id="imageInput" type="file" />
<input type="submit" id="submit-btn" onClick="uploadAvatar();" value="Upload" />
And finally this is my PHP code (I have nothing here)
$thumb_square_size = 200;
$max_image_size = 500;
$thumb_prefix = "thumb_";
$destination_folder = './data/avatars/';
$jpeg_quality = 90; //jpeg quality
$return_json = array();
if($err==""){ $return_json['msg'] = $msg; }
else{ $return_json['err'] = $err; }
echo json_encode($return_json);
exit;
So how do I start this really. I just don't know where to start, I don't know exactly what to do.
Bulletproof is a nice PHP image upload class which encorporates common security concerns and practices, so we will use it here as it also makes the whole process much simpler and cleaner. You will want to read the approved answer on this question here (https://security.stackexchange.com/questions/32852/risks-of-a-php-image-upload-form) to better understand the risks of accepting file uploads from users.
The PHP below is really basic and really only handle the image upload. You would want to save the path or the file name that was generated in a database or in some kind of storage if the image is uploaded successfully.
You may also want to change the directory in which the image is uploaded to. To do this, change the parameter for ->uploadDir("uploads") to some other relative or absolute path. This value "uploads" will upload the image to the libraries/ajax/uploads directory. If the directory does not exist, bulletproof will first create it.
You will need to download bulletproof (https://github.com/samayo/bulletproof) and make sure to upload or place it in libraries/bulletproof/. When you download the class from github it will be in a ZIP archive. Extract the zip archive and rename bulletproof-master director to just plain bulletproof. Place that directory in the libraries directory.
HTML
<form id="avatar_form" action enctype="multipart/form-data" method="post">
<input name="image_file" id="imageInput" type="file" />
<input type="submit" id="submit-btn" value="Upload" />
</form>
JS
$('#avatar_form').submit(function( event ){
event.preventDefault();
var formData = new FormData($(this)[0]); //use form data, not serialized string
$('#avatarDialog').fadeIn();
$('#avatarDialog').html("Logging in, please wait....");
$.ajax({
type: "POST",
url: site_url + "/libraries/ajax/image-upload.php",
data: formData,
cache: false,
contentType: false,
processData: false,
success: function(data){
if(data.code != 200){ //response code other than 200, error
$('#avatarDialog').fadeIn();
$('#avatarDialog').html(data.msg);
} else { // response code was 200, everything is OK
$('#avatarDialog').fadeIn();
$('#avatarDialog').html(data.msg);
var delay = 2000;
window.setTimeout(function(){
location.reload(true);
}, delay);
}
}
});
return false;
});
PHP
//bulletproof image uploads
//https://github.com/samayo/bulletproof
require_once('../bulletproof/src/bulletproof.php');
$bulletproof = new ImageUploader\BulletProof;
//our default json response
$json = array('code' => 200, 'msg' => "Avatar uploaded!");
//if a file was submitted
if($_FILES)
{
try
{
//rename the file to some unique
//md5 hash value of current timestamp and a random number between 0 & 1000
$filename = md5(time() . rand(0, 1000));
$result = $bulletproof->fileTypes(["png", "jpeg"]) //only accept png/jpeg image types
->uploadDir("uploads") //create folder 'pics' if it does not exist.
->limitSize(["min" => 1000, "max" => 300000]) //limit image size (in bytes) .01mb - 3.0mb
->shrink(["height" => 96, "width" => 96]) //limit image dimensions
->upload($_FILES['image_file'], $filename); // upload to folder 'pics'
//maybe save the filename and other information to a database at this point
//print the json output
print_r(json_encode($json));
}
catch(Exception $e)
{
$json['code'] = 500;
$json['msg'] = $e->getMessage();
print_r(json_encode($json));
}
}
else
{
//no file was submitted
//send back a 500 error code and a error message
$json['code'] = 500;
$json['msg'] = "You must select a file";
print_r(json_encode($json));
}
Bulletproof will throw an exception if the image does not pass the validation tests. We catch the exception in the try catch block and return the error message back to the JavaScript in the JSON return.
The rest of the code is commented pretty well from the Bulletproof github page etc, but comment if anything is not clear.