Control image upload size in textarea of HTML Form - javascript

I'm using the following WIZWIG editor "http://js.nicedit.com/nicEdit-latest.js" posting into the below HTML form. I want to control the size of images that are uploaded. Image size should be something like 200px height, 300px width. I've tried CSS, HTML & JavaScript to no avail. Can't figure this out...
<style>
.nicEdit-main{
background-color: white;
}
</style>
<script type="text/javascript" src="http://js.nicedit.com/nicEdit- latest.js"></script>
<script type="text/javascript">
bkLib.onDomLoaded(function() { nicEditors.allTextAreas({buttonList : ['bold','italic','underline','strikeThrough','html','forecolor','link','upload','unlink','removeformat']}) });
</script>
<form name="comments" action="<?php echo $_SERVER['PHP_SELF']; ?>"method="post" onsubmit="return checkForm();">
<?php if ($isGuest) { ?>
Comment:<br><br>
<div style="background: #fff;">
<textarea style="width: 100%;" name="comment" cols="111px" rows="4">disabled for guest account</textarea>
</div>
<input type="submit" name="action" disabled value="Add Comment" />
<?php } else { ?>
Comment:<br><br>
<div style="background: #fff;">
<textarea style="width: 100%;" name="comment" cols="111px" rows="4"></textarea>
</div>
<input type="submit" name="action" value="Add Comment" />
<?php //header("Location: test.php");
} ?>
</form>

Although this was not possible few years ago(you had to send the file to the server side to be able to process file information) now it is do possible with the FileReader() object and pure JS.
You use the .files[0] to get the file then create a temporary img object on the DOM(to be able to do the process) and then assign the file to that DOM object(with the help of FileReader())and then you just compare the file width or height. This is an example how you can do it:
imgfile.onchange = function(e) {
var oFile = document.getElementById("imgfile").files[0]; //Get the selected file by the user
var img = document.getElementById("imgdom"); //get the reserve image element on the dom to be able do all our processing with this object type
document.getElementById("imgdom").style.display = "none";//This is optional if you want to show or not the image to the user
var reader = new FileReader(); //This is the magic object that allows you to process a file on the client side
reader.onload = function (e) {
console.log(e.total); // file size
img.src = e.target.result; // putting file in dom without server upload.
alert(img.width);
//Do what ever condition you want here
//if img.width > 200 do this, else do that
};
reader.readAsDataURL(oFile );
//return false;
};
<form method="post" enctype="multipart/form-data" onsubmit="return false;">
<input type="file" name="imgfile" id="imgfile">
</form>
<div>
<img id="imgdom" src="" />

This issue has been resolved with the following CSS Code:
.nicEdit-main img {
width: 350px;
}
img[src*="http://somedomain.com"] {
width: 350px;
}
Thanks to all who commented...

Related

Is it Possible to make a button as File upload Button?

I am new in php. I have a form on which i place a button Value as Upload MB when user click on this button it redirects on a web form where i place a file upload control and user upload file here.
Here is image
After clicking this button user redirect on this form
here user upload file.
MY QUESTION
Is it possible that can i make my button Upload Mb as file upload button? Can it works like file upload control button?
Actually i want to save user time. I want that when user click on Upload MB button it not redirects on Form. But when user Click on Upload MB button it allow to user to upload file and open browsing window. After that when user upload file it redirects on form.
Can you guys tell me it is possible or not?
You can keep a <input type='file' hidden/> in your code and click it using javascript when the user clicks on the "Upload MB" button.
Check out this fiddle.
Here is the snippet.
document.getElementById('buttonid').addEventListener('click', openDialog);
function openDialog() {
document.getElementById('fileid').click();
}
<input id='fileid' type='file' hidden/>
<input id='buttonid' type='button' value='Upload MB' />
Here is the complete code.
<html>
<head>
<script>
function setup() {
document.getElementById('buttonid').addEventListener('click', openDialog);
function openDialog() {
document.getElementById('fileid').click();
}
document.getElementById('fileid').addEventListener('change', submitForm);
function submitForm() {
document.getElementById('formid').submit();
}
}
</script>
</head>
<body onload="setup()">
<form id='formid' action="form.php" method="POST" enctype="multipart/form-data">
<input id='fileid' type='file' name='filename' hidden/>
<input id='buttonid' type='button' value='Upload MB' />
<input type='submit' value='Submit' />
</form>
</body>
</html>
my 2 cents to the topic: all in code, no input needs to be added to the page.
function onClickHandler(ev) {
var el = window._protected_reference = document.createElement("INPUT");
el.type = "file";
el.accept = "image/*";
el.multiple = "multiple"; // remove to have a single file selection
// (cancel will not trigger 'change')
el.addEventListener('change', function(ev2) {
// access el.files[] to do something with it (test its length!)
// add first image, if available
if (el.files.length) {
document.getElementById('out').src = URL.createObjectURL(el.files[0]);
}
// test some async handling
new Promise(function(resolve) {
setTimeout(function() { console.log(el.files); resolve(); }, 1000);
})
.then(function() {
// clear / free reference
el = window._protected_reference = undefined;
});
});
el.click(); // open
}
#out {
width: 100px; height: 100px; object-fit: contain; display: block;
}
/* hide if it would show the error img */
#out[src=''] {
opacity: 0;
}
<img src="" id="out" />
<button onClick="onClickHandler(event)">select an IMAGE</button>
Note: the el might get garbage collected, before you process all data - adding it to window.* will keep the reference alive for any Promise-handling.
I would suggest to convert button to label. apply the css to label so that it looks like button.
e.g. -
<input type="file" id="BtnBrowseHidden" name="files" style="display: none;" />
<label for="BtnBrowseHidden" id="LblBrowse">
Browse
</label>
Bootstrap Way
.choose_file {
position: relative;
display: inline-block;
font: normal 14px Myriad Pro, Verdana, Geneva, sans-serif;
color: #7f7f7f;
margin-top: 2px;
background: white
}
.choose_file input[type="file"]{
-webkit-appearance:none;
position:absolute;
top:0;
left:0;
opacity:0;
width: 100%;
height: 100%;
}
<div class="choose_file">
<button type="button" class="btn btn-default" style="width: 125px;">Choose Image</button>
<input name="img" type="file" accept="image/*" />
</div>
<html>
<body>
<input type="file" id="browse" name="fileupload" style="display: none" onChange="Handlechange();"/>
<input type="hidden" id="filename" readonly="true"/>
<input type="button" value="Upload MB" id="fakeBrowse" onclick="HandleBrowseClick();"/>
</body>
<script>
function HandleBrowseClick()
{
var fileinput = document.getElementById("browse");
fileinput.click();
}
function Handlechange()
{
var fileinput = document.getElementById("browse");
var textinput = document.getElementById("filename");
textinput.value = fileinput.value;
}
</script>
</html>
There's an experimental feature that does exactly what you are looking for. You can take a look at it here: https://developer.mozilla.org/en-US/docs/Web/API/Window/showOpenFilePicker

Uploading multiple images within a json call

I'm trying to modify a jquery script I use often in my websites to integrate image uploads within it. Maybe it's a script that cannot be modified for this purpose otherwise I could do with some help. I dont really understand the 64 bit encoding for json and if it is possible to upload an image with json data in parrallel so I can benefit from the success responce without reloading pages. I would also like to avoid the plugins such as uploadify etc if possible. Also I'm uploading to folders/diectories listed in my html code, using checkboxes to hide and show elements and to identify the folder path for images.
my jquery
<script type="text/javascript">
$(document).ready(function() {
var checkboxes = $("input[type='checkbox']");
checkboxes.click(function() {
$('#add_photo_but').show();
$('#photoChoose').show();
$('#addPhotoInstruction').hide();
});
$(".add_photo_but").click(function() {
var file = $("image").files[0];
var image = $("#addImage").val();
$.post("includes/add_photo.inc.php",{ checked_box : $('input:checkbox:checked').val(), image:image, imageFile:file},function(json) {
if(json.result === "success") {
$(".addPhoto_result").html(json.message);
//$(".checkbox")[0].remove();
$("input:checkbox:checked").parent().remove();
// $('.add_intern').get(0).reset();
}else{
$(".addPhoto_result").html(json.message);
}
});
});//submit click
});//doc ready
</script>
html form
<div id="photos">
<form enctype="multipart/form-data" name="add_photo" class="add_photo">
<?php
while($row = mysqli_fetch_array($result4)){ ?>
<div class="photoAlbum_list">
<div id="#photoAlbumId" class="albumPhoto"><?php echo $row['album_name'];?></div>
<img src="image/mandinga_folder.png" class="folder"/>
<input type="checkbox" class="photoAlbumId" id="photoAlbumList" value="<?php echo $row['albumid'];?>"/>
</div>
<?php } ?>
</form>
<div id="addPhotoInstruction" style="display:block">Please choose an Album to Upload Photo's to</div>
<div class="addPhoto_result"></div>
<input id="photoChoose" type="file" multiple style="display:none"/>
<input type="button" id="add_photo_but" class="add_photo_but" name="add_photo_but" value="Add Photo" form="add_photo" style="display:none"/>
</div>

Fault with appending item to drop down (local storage)

I have the following code, which works well.
<div style="padding:2px;">
<form action='test.php' name ='gen' method='post'>
<input type='text' name='pass' placeholder="Insert website" size="10"> <input type='submit' value='Open'>
</form>
</div>
<?php
$random = 'specificsaltcode'; // specific salt
$pass2 = $_POST['pass'] . $random; // add it to user input
$pass = md5($pass2); // md5() both
$url = 'http://www.website'.$_POST['pass'].'random'.$pass.'randomurlcontinued'; // the url you need
echo '<iframe id="iframe1" name="iframe1" scrolling="yes" src="' . $url . '" style="position: absolute; left: 0px; top: 26px;" width="99%" height="88%" border="0"></iframe>';
?>
This hashes a user input string and sends the original input string, along with the hashed number to an iframe as a url. This works well for me.
However, rather than send the url to an iframe, I need to send this to a drop down list and store it using local storage.
I have the following code for my drop down.
<style>
#choice option { color: black; }
.empty { color: gray; }
</style>
<script>
var VM = function () {
this.annotationList = ko.observable();
this.area = ko.observableArray();
this.append = function () {
this.area.push(this.annotationList());
localStorage.setItem('labelObject',this.annotationList());
localStorage.setItem('labelObjectList',this.area());
};
};
var existAnnotationmodel = new VM();
ko.applyBindings(existAnnotationmodel);
</script>
<script>
$("#choice").change(function () {
if($(this).val() == "0") $(this).addClass("empty");
else $(this).removeClass("empty")
});
$("#choice").change();
</script>
<form >
<span class="btn-group">
<select name="select" data-bind="options: area" id="choice">
<option value="0" selected="selected">Choose website</option>
</select>
<input id="editExistannotation" data-bind="value: annotationList" type="text" placeholder="Enter website"/>
</span>
<button id="buttonSave" type="submit" data-bind="click:append" >Save</button>
</form>
<div id="labelList" class="btn-group" ></div>
However, this drop down method does NOT store these appends. Infact, it doesn't even add any items to the menu at all. I'd like it to add an item to the drop down, and save it using local storage, so when the user refreshes the page, the appends are still there.
So two issues, how to pass the url to the drop down, and how to make the drop down save appended items.
Also, I am not concerned over security issues at the moment.

Through image I browsed images but not able to submit the same

Through image I want to browse images for that I have taken div and hided the field img_photo and called a function i.e OpenFileBrowser() on anchor tab. I am able to browse images but not able to submit the form.
HTML :
<form name="frmimg" id="frmimg" method="post" action="abc.php">
<div style="display:none"><input type="file" name="img_photo" id="img_photo" value="" accept="image/gif, image/jpeg, image/jpg, image/png"></div>
<a href="wap_statusupadate.php?img=<?php echo $_REQUEST['hid_img']; ?>" onclick="return OpenFileBrows
er('frmimg')"><img src="images/photo-icon.jpg" /></a>
</form>
Javascript :
function OpenFileBrowser(obj)
{
document.getElementById('img_photo').click();
var img = document.getElementById('img_photo').value;
if(img!="")
{
document.obj.submit();
}
else
{
return false;
}
}
Try adding
document.getElementById('frmimg').submit();
to the end of function OpenFileBrowser(obj).

IFRAME file upload is not working

I want to upload file and idno using iFrame concept using PHP. I used this code with my project.
This code alone is working fine. The file is uploading. But when it is in my project, it is not working. It showing
undefined index myfile
(I always test in Firefox browser.)
Even an extra parameter idno is also not sending...
But in the same page HTML5 Drag and Drop is working.
any Help?
Here is my code:
<form method="post" action="Nupload.php" enctype="multipart/form-data" class="manual" id="upload_form" target="upload_target">or
<input type="file" name="myfile" id="myfile" style="display:none" onchange="javascript:getReady();" />
<label for="file">select files from your computer...</label>
<input type="hidden" name="idno" value="2013456" />
<iframe src="Nupload.php" name="upload_target" id="upload_target" style="display:none;">
</iframe>
</form>
Script:
function getReady()
{
document.getElementById("upload_target").onload = uploadDone();
document.getElementById("upload_form").submit();
}
function uploadDone()
{
var content="";
var iframeId=document.getElementById("upload_target");
if (iframeId.contentDocument) {
content = iframeId.contentDocument.body.innerHTML;
} else if (iframeId.contentWindow) {
content = iframeId.contentWindow.document.body.innerHTML;
} else if (iframeId.document) {
content = iframeId.document.body.innerHTML;
}
alert(content)
}
upload.php
if( isset($_FILES["myfile"]) )
{
$target = basename($_FILES["myfile"]["name"]);
if(move_uploaded_file($_FILES["myfile"]["tmp_name"],"./temp/".$target))
{
$res = array("success"=>true,"file_name"=>$_FILES["myfile"]["name"],"size"=>$_FILES["myfile"]["size"]);
}
else
$res = array("success"=>false,"desc"=>"no");
echo json_encode($res);
}

Categories