JavaScript upload size limit - javascript

so I'm trying to set up upload size limit, but it has been unsuccessful.
I have included the code with explanations, please hava a look and I would be very thankfull if you could help me.
More information on wha I needм help with is after the " // "
Here's the code: `
<html>
<p id="check"></p>
//ok so this part of <script> sends the user to "email.html"
<script type="text/javascript">
function getFile(){
document.getElementById("file").click();
}
function sub(obj){
var file = obj.value;
document.myForm.submit();
}
</script>
//here's the code for the button to upload a file (or image in my case)
<form action="e-mail.php" method="post" enctype="multipart/form-data" name="myForm">
<div id="yourBtn" onclick="getFile()">Yes</div>
<div style="text-align: center; overflow: hidden;">
<input type="file" value="upload" id="file" accept="image/*"
onchange="sub(this)"
size="1" style="margin-top: -50px;" "margin-left:-410px;" "-moz-opacity: 0;
"filter:
alpha(opacity=0);" "opacity: 0;" "font-size: 150px;" "height: 100px;">
</div>
</form>
<script>
var attachement = document.getElementById('file');
attachement.onchange = function() {
var file = attachement.files[0];
if (file.size < 1000000) {
function sub(obj){return true; }
//ok so here's the problem,
when I include this code between
'script' the user is not taken
to "e-mail.html" anymore... please help!!!
else { return false;}
}
}
</script>
</html> `
Thanks a lot:)

To go to a different page when the file is too big, you can assign the new URL to document.location. Note that the URL should be absolute (i.e. http://.../email.html).
I suggest to display an error when the file is too big and simply not submit the page. Otherwise, the user will see the new page and believe that everything was all right.
Also note that you need to do the same check on the server because an attacker might just create a POST request from scratch (without using the code from your page) to send files of arbitrary size to your server.

Because the funtion inside of the onchange is not global. It is only available to the onchange.
would would need to change it to
window.sub = function (obj){return true; }
BUT the flaw with this is the user can change the file a second time and submit since you just removed the return false. You could either add it back in on the else OR you can do validation when the form is submitted and not onchange.

Related

How to Change Background Image Based on User Input | HTML, CSS, JS

I have done a lot of research on how to do this, yet I can't seem to find a specific answer. I am trying to allow the user to input a file from their computer, and turn that file into the background of the webpage. My following code is shown below:
<head>
<script>
function changeBackground() {
var input = document.getElementById("background").value;
localStorage.setItem("Background", input);
var result = localStorage.getItem("Background");
$('body').css({ 'background-image': "url(" + result + ")" });
}
</script>
</head>
<body>
<input id="background" type="file" onchange="changeBackground()">
</body>
If someone could please explain to me what I need to do to get this to work, I would very much appreciate it. I already understand I need to use localStorage to make sure that the selected background is remembered, I am just having trouble getting the background to change. If there is already an article on how to do this, I would appreciate a link to it. Thanks!
EDIT
Nikhil and user6003859 explained to me why it isn't working. I guess I just need to figure out how to use Ajax and PHP to change it. If anyone has more advice on this, I would love to hear it. Thanks everyone for helping me solve this problem.
Modern browsers normally restrict access to the user's local files (in this case an image). What you're trying to do is display an image from the user's local filestorage, via the path you get from the <input type='file' /> value.
What you should instead be doing, is uploading the image to your server (probably with ajax, so it feels seamless), and then displaying the file from your server on to your page.
EDIT: Even though this is kind of a new question, I'll give you an example on how to change an element's background based on a URL provided by the user:
var inp = document.getElementById('inp');
var res = document.getElementById('res');
inp.oninput = function()
{
res.style.backgroundImage = 'url(' + inp.value + ')';
};
div
{
width: 5em;
height: 5em;
}
<input type='text' id='inp' />
<div id='res'>
</div>
It's better practice to use file reader.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#file").change(function(){
var length=this.files.length;
if(!length){
return false;
}
changeBackground(this);
});
});
// Creating the function
function changeBackground(img){
var file = img.files[0];
var imagefile = file.type;
var match= ["image/jpeg","image/png","image/jpg"];
if(!((imagefile==match[0]) || (imagefile==match[1]) || (imagefile==match[2]))){
alert("Invalid File Extension");
}else{
var reader = new FileReader();
reader.onload = imageIsLoaded;
reader.readAsDataURL(img.files[0]);
}
function imageIsLoaded(e) {
$('body').css({ 'background-image': "url(" + e.target.result + ")" });
}
}
</script>
</head>
<body>
<input type="file" name="" id="file" value="Click">
</body>
</html>
You cannot do that purely with client-side because of security reasons.
The moment you upload say an image, the browser gives it a "fakepath" like so:
C:\fakepath\<filename>.png
This is a security implementation of the browser - the browser is protecting you from accessing your disk structure.
Hence when you check the value of your input after uploading, you would get the above fakepath ie. C:\fakepath\<filename>.png. Using this as the background obviously would not work.
Usually to achieve this you need to first store it in a server, then fetch the value from the server and apply the background.
To use a local file, store it in a blob
<head>
<script>
function changeBackground() {
var backgroundFile = document.getElementById("background").files[0];
$('body').css({ 'background-image': "url(" + URL.createObjectURL(backgroundFile) + ")" });
}
</script>
</head>
<body>
<input id="background" type="file" onchange="changeBackground()">
</body>

Why I lost the filename value when I click the submit button

I have made a form to pass xml files on a server. Although when it correctly sends the file to the server, it seems that the pages reloads and the value of the file name is lost and my javascript code returns nothing.
However if I remove the line
<input type="submit" />
from the code below it keeps the filename in the variable x but it doesn't send the file to the server.
I want to send the file on the server and keep its name into a variable in order to use in any other javascript functions.
<?php
$uploads_dir='/web/stud/external/scomvs2/epicurus';
if(isset($_FILES['xml_file1'])){
$errors= array();
$file_name = $_FILES['xml_file1']['name'];
$file_size =$_FILES['xml_file1']['size'];
$file_tmp =$_FILES['xml_file1']['tmp_name'];
$file_type=$_FILES['xml_file1']['type'];
$file_ext=strtolower(end(explode('.',$_FILES['xml_file1']['name'])));
$expensions= array("xml","XML");
if(in_array($file_ext,$expensions)== false){
$errors[]="extension not allowed, please choose an xml file.";
}
if($file_size > 2097152){
$errors[]='File size must be excately 2 MB';
}
if(empty($errors)==true){
move_uploaded_file($file_tmp,"$uploads_dir/$file_name");
echo "Success";
}else{
print_r($errors);
}
}
?>
<html>
<body>
<form action="" method="POST" enctype="multipart/form-data">
<input type="file" id="uploading" name="xml_file1"/>
<input type="submit" />
</form>
<button type="button" onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var x = document.getElementById("uploading").value;
document.getElementById("demo").innerHTML = x;
}
</script>
</body>
</html>
You can add in our Javascript part the following:
<script>
function myFunction() {
var x = <?=json_encode($file_name)?>;
document.getElementById("demo").textContent = x;
}
</script>
Now when in Javascript you call that function, the demo element will show the file name. Note that it is better to use textContent instead of innerHTML, although with filenames you don't risk to have special characters that HTML would interpret (<>&).
Now you should also make sure that $file_name is always defined. So at the top of your PHP code, add:
$file_name = '';
Instead of injecting the file name in your Javascript code, you could also let it be injected directly in the demo tag, like this:
<p id="demo"><?=htmlspecialchars($file_name)?></p>
Then you don't need Javascript to fill it in, if that is all you wanted to do.

How to pass Variable from External JavaScript to HTML Form

I have been trying to pass a value from an external javascript file to an HTML form with no luck. The files are rather large so I am not sure I can explain it all but ill try.
Basically a user clicks a link then a js file is initiated. Immediately after a new HTML page loads.
I need this value passed to the HTML page in a form field.
Javascript:
var divElement = function(){
divCode = document.getElementById(div1).innerHTML;
return divCode; };
document.getElementById('adcode').value = divElement();
Afterwards it should be passed to this Form field
HTML Form Field:
<p>Ad Code:<br>
<input type="text" name="adcode" id="adcode"/>
<br>
</p>
Thanks for any help!
Your HTML file needs to reference the JavaScript js file. Have a function in your JavaScript that returns the value that you need. Use JavaScript (I like jQuery) to set the form field to what you need.
JS file:
<script>
var divElement = function(){
divCode = document.getElementById(div1).innerHTML;
return divCode; };
document.getElementById('adcode').value = divElement();
function GetDivElement() {
return divElement();
}
</script>
HTML file:
<p>Ad Code:
<br />
<input type="text" name="adcode" id="adcode"/>
<br />
</p>
<script src="wherever that js file is" />
<script>
window.onload = function() {
document.getElementById('adcode').value = GetDivElement();
}
</script>
Although, really, this might do what you want (depending on what you are trying to do):
<p>Ad Code:
<br />
<input type="text" name="adcode" id="adcode"/>
<br />
</p>
<script src="wherever that js file is" />
<script>
window.onload = function() {
GetDivElement();
}
</script>
Can it be this?:
function divElement(divCode){
return divCode;
}
divElement(document.getElementById('adcode').value);

post form values to html

I want to POST form values and display them on another html page using Javascript. No server-side technology should be used. I have a function that posts the values but to read the values to another html page, I think I am missing something. Below is the code.
Any help? Thanks in advance.
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Untitled Page</title>
<script type="text/javascript">
function post_to_page(path, params, method) {
method = method || "post"; // Set method to post by default, if not specified.
var form = document.createElement("form");
form.setAttribute("method", method);
form.setAttribute("action", path);
form.setAttribute("target", "formresult");
for (var key in params) {
if (params.hasOwnProperty(key)) {
var hiddenField = document.createElement("input");
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", key);
hiddenField.setAttribute("value", params[key]);
form.appendChild(hiddenField);
}
}
document.body.appendChild(form);
// creating the 'formresult' window with custom features prior to submitting the form
window.open('target.htm', 'formresult', 'scrollbars=no,menubar=no,height=600,width=800,resizable=yes,toolbar=no,status=no');
form.submit();
}
</script>
</head>
<body>
<form id="form1" action="target.htm" method="post">
<div>
USB No: <input name="usbnum" id="usbnum" type="text"/><br />
USB Code: <input name="usbcode" id="usbcode" type="text"/>
</div>
<button onclick="post_to_page()">Try it</button>
</div>
</form>
</body>
</html>
Here is a simple example of moving data from one Window to another
<!-- HTML -->
<textarea id="foo"></textarea><br/>
<input id="bar" value="click" type="button"/>
and the real code to make it work, which assumes you pass the same origin policy
// JavaScript
var whatever = 'yay I can share information';
// in following functions `wnd` is the reference to target window
function generateWhatever(wnd, whatever) { // create the function actually doing the work
return function () {wnd.document.getElementById('foo').innerHTML = whatever};
} // why am I using a generator? You don't have to, it's a choice
function callWhenReady(wnd, fn) { // make sure you only invoke when things exist
if (wnd.loaded) fn(); // already loaded flag (see penultimate line)
else wnd.addEventListener('load', fn); // else wait for load
}
function makeButtonDoStuff() { // seperated button JS from HTML
document
.getElementById('bar')
.addEventListener('click', function () {
var wnd = window.open(window.location); // open new window, keep reference
callWhenReady(wnd, generateWhatever(wnd, whatever)); // set up function to be called
});
}
window.addEventListener('load', function () {window.loaded = true;}); // set loaded flag (do this on your target, this example uses same page)
window.addEventListener('load', makeButtonDoStuff); // link button's JavaScript to HTML when button exists
You can't get POST values using JavaScript. You can use GET method to pass values.
If you are using html5 you can use localStorage. Otherwise a query string or cookies are your other options.
You said you didn't want the server involved...why are you calling submit?
[Edit]
#Paul S's comment/answer looks very helpful. But you might look at something like the jQuery PostMessage plugin if you need it to be cross browser compatible.
http://benalman.com/projects/jquery-postmessage-plugin/
You don't require a POST request to send data from one page to another. Simply use LocalStorage to do the trick. Just call a Javascript function on form submission. This may help:
HTML:
<form id="form1" action="target.htm" method="post">
<div>
USB No: <input name="usbnum" id="usbnum" type="text"/><br />
USB Code: <input name="usbcode" id="usbcode" type="text"/>
</div>
<button onclick="post_to_page()">Try it</button>
</form>
Javascript:
function post_to_page() {
localStorage.value = "Your content here";
window.location = "nextpage.html";
}
This will save the data locally and go to the next page. In the next page, simply call this function to retrieve the stored data:
function get_stored_data() {
alert(localStorage.value);
}
You can simply assign it to a div, textbox other Javascript variable.

Hidden form file POST in javascript

Because of a Flex bug uploading files in a secure environment, I'm attempting to hack together a workaround for this in javascript.
To do so, I'm attempting to create a hidden form in javascript, to which I'll attach a file and some xml meta data, then send it to the server in a multipart form post. My first thought is to get this to work in HTML and then port this javascript code into my Flex project.
My first problem is attaching the file to the hidden form in javascript. I'm doing something wrong here. I'm pretty inexperienced with javascript so if there's a better way to do this, I'm eager to learn.
Here's the code I'm current playing with.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>hidden form post demo</title>
</head>
<body>
<script>
//helper function to create the form
function getNewSubmitForm(){
var submitForm = document.createElement("FORM");
document.body.appendChild(submitForm);
submitForm.method = "POST";
submitForm.enctype = "multipart/form-data";
return submitForm;
}
//helper function to add elements to the form
function createNewFormElement(inputForm, inputType, elementName, elementValue) {
var inputElement = document.createElement("INPUT");
inputElement.name = elementName;
inputElement.type = inputType;
try {
inputElement.value = elementValue;
} catch(err) {
alert(err.description);
}
inputForm.appendChild(inputElement);
return inputElement;
}
//function that creates the form, adds some elements
//and then submits it
function createFormAndSubmit(){
var submitForm = getNewSubmitForm();
var selectedFileElement = document.getElementById("selectedFile");
var selectedFile = selectedFileElement.files[0];
createNewFormElement(submitForm, "HIDDEN", "xml", "my xml");
createNewFormElement(submitForm, "FILE", "selectedFile", selectedFile);
submitForm.action= "my url";
submitForm.submit();
}
</script>
<div id="docList">
<h2>Documentation List</h2>
<ul id="docs"></ul>
</div>
<input type="file" value="Click to create select file" id="selectedFile"/>
<input type="button" value="Click to create form and submit" onclick="createFormAndSubmit()"/>
</body>
</html>
You can see, I have a try/catch block in createNewFormElement. An exception is being thrown there, but the message says "undefined".
In FireBug, I can see that the elementValue is set to a File object, so I'm not really sure what's going on.
For security reasons, you cannot set the value attribute of an input[type=file]. Your current code doesn't need JavaScript, and can be written using pure HTML:
<form method="post" enctype="multipart/form-data" action="myurl">
<input type="file" value="Click to create select file" name="selectedFile" />
<input type="hidden" name="xml" value="my xml" />
<input type="submit" value="Click to create form and submit" />
</form>
If you want to, it's possible to dynamically add additional non-file form elements, by binding an event to the onsubmit handler.
<form ... onsubmit="addMoreinputs();" id="aForm">
...
<script>
function addMoreInputs(){
var form = document.getElementById("aForm");
// ...create and append extra elements.
// once the function has finished, the form will be submitted, because
// the input[type=submit] element has been clicked.
}
add
var dom=document.getElementById("formdiv");
dom.appendChild(submitForm);
in your createFormAndSubmit function.
and add <div id="formdiv" /> on your page.

Categories

Resources