Adapt html5 file uploader to use known file URL instead? - html

I am trying to adapt an html5 file uploader (from tutorial) so it can submit an image URL (already held in a javascript variable) instead of asking the user to browse for a local file.
I believe the relevant code to adapt (but I might be wrong) is:
<input type="file" name="image_file" id="image_file" onclick="" onchange="fileSelectHandler()" />
Taken from tutorial: http://www.script-tutorials.com/html5-image-uploader-with-jcrop/
My end process will be:
Browse facebook albums and obtain gallery image to javascript variable (jquery.getfacebookalbums.js) - PASS (I can already Alert the URL of chosen file)
Adapt the HTML5 file uploader as used in the tutorial, to push the stored facebook image URL instead of a file. (And it would be ideal to be able to do this without redundant button clicks, since file url is already present to input)
Many thanks!
UPDATE:
My attempts at a starting point to achieve this have failed.
In my main html page I have a javascript variable storing full path to .jpg
The original post sequence was:
(html file)
(.js file)
function fileSelectHandler() {
// get selected file
var oFile = $('#image_file')[0].files[0];
...
And variations I've tried to post a stored javascript variable .jpg URL are:
(html file javascript)
alert("image_file is" + image_file);
fileSelectHandler();
or
<form action="fileSelectHandler()">
URL: <input type="text" name="image_file" id="image_file" value="splashScreen.jpg">
<input type="submit" value="Submit form">
</form>
As starting points.
...And I would like to be able to Alert from the fileSelectHandler() in the .js file as to what value it has received for: var oFile = $('#image_file')[0].files[0]; so I can more easily understand what is being passed - but alert(oFile) or alert($('#image_file')) is being ignored.
Thanks in advance!

Related

HTML form with GET method to PDF file ignores query string

I have this simple web form which has just a single button so the user can open a static PDF file when they click it.
Now that I've updated the PDF file, I updated the query string timestamp cache-busting parameter so they see a new version of the file.
<form action="Path/To/My/PDF Document.pdf?v=1234" target="_blank">
<button>Get your PDF here!</button>
</form>
Well, the PDF opens up alright, but the querystring is automatically reduced to just the question mark.
What opens up is: Path/To/My/PDF Document.pdf?
This shows the original version and not the new one, and I'm wondering what is the matter with this process?
*I know method="GET" is not in my example, but it does the same with or without it.
Give this a go:
<form
action="Path/To/My/PDF Document.pdf"
method="GET">
<input type="hidden" name="v" value="1234" />
<button>Get your PDF here!</button>
</form>
Key points:
specify the method as GET
provide the query-string parameter as a hidden input, with the name set to the name of the query-string
The reason this works is because of how forms process input data.
Demo: https://jsfiddle.net/1tszbe5o/
Recommended reading for WHY this works: https://developer.mozilla.org/en-US/docs/Learn/Forms/Sending_and_retrieving_form_data
TLDR: when you use the GET method, any form data provided with form inputs will be included in the query-string of the HTTP request resulting from the form action.
Why does it get stripped out in the first place? Because the form data was empty, hence the query-string was empty also ;)

form action="your-shop" : what does this mean without file extension?

I have seen filename(with file extension) or URL inside action attribute but never seen anything like this code below.
<form action="your-shop" name="shop_name_form" id="shop_name_form" method="post" onsubmit="return check_shopname(this);">
</form>
Here action attribute contains may be a file name but no file name extension.
What will it do when i press submit button?please explain it in details
It's a relative URL and will be resolved against the current URL. E.g. If the page is located at http://example.com/current/path/foo, the from will be submitted to http://example.com/current/path/your-shop.
File extensions have no meaning in a URL, how the path is processed depends on the server implementation.
At first it calls the Javascript function check_shopname();.
If it returns false, the submit will be canceled, so maybe there is no case where true is returned, because the Admin handles all the things on the client side!
The second possibility is, that the url of the sites are modified by mod_rewrite, and you get redirected to another file, for example, by adding a .html or .php extension.
If you will take you to the following link for form submission.
www.yourwebsite.com/your-shop. your-shop will be appeneded to the website's URL. Since there is no folder or other directory included. As Felix has mentioned already in comments, the File extension like .html has no meaning here in this context of action.

Set file path for input type="file"

Can we set the file path in javascript for
<input name="pictureUL" type="file" value="upload" onChange="this.form.submit()"/>
without opening the select file dialog box?
I have 2 buttons SCAN and FIND. ADD button opens dialog box asking user to select the file which will be uploaded to the server. SCAN button has to scan the document and upload it to the server. Scanning is fine but to submit the form i need to set the file path in the file tag as i am submitting the form there. Is there a way to do it?
Thanks in advance.
Due to possibly security issues, modern browsers do not allow you to access the file path or modify the value of an <input type="file">. You also cannot view the file path, as it will display C:\fakepath\yourfilename.yourfilextension.
You can't do it directly but you can create your new Filelist using a DataTransfer object, and if you wish you can copy your data into it to and create a duplicate with the specific change you want to make.
let file = new File([blob], fileName);
let list = new DataTransfer();
list.items.add(file);
You can then set it as the file attribute of the DOM node:
fileInput.files = myFileList;

Need jsp form to submit query to specific path

I'm trying to setup a simple form in a jsp that will put a search query in the URL submitted.
This is what I have so far:
<form action="search/" method="get" onsubmit="this.action+=this.q.value.trim();return true">
<input type="text" id="q">
<input type="submit" value="go">
</form>
This is in a jsp that's included on each page of my web app and it works when I'm at the root of the app. For example, if I initially load "http://localhost:8080/MyApp/" then type "123456" in the search form, it takes me to "http://localhost:8080/MyApp/search/123456", which is what I want. However, from that page, if I search again (for "654321" for example) it goes to "http://localhost:8080/MyApp/search/search/654321", which doesn't work for me. I need search/{query} to be appended to the root of the app's path no matter what page I may be on at the time.
I would like to avoid javascript if possible, I'm fine with JSTL though.
Any suggestions would be much appreciated!
Simply add a full path to your action, start it with /. Note it will depend on your application context, you could use :
<form action="${pageContext.request.contextPath}/search/"...
It will work in dev and also prod.
EDIT :
Path : search will try to load relative from current path so : http://domain.com/contact/search/
Path : /search will try to load relative from the domain so : http://domain.com/
With the context path above, it will work no matter if it change from dev to prod.
Hope this helps!

Limit file format when using <input type="file">?

I'd like to restrict the type of file that can be chosen from the native OS file chooser when the user clicks the Browse button in the <input type="file"> element in HTML. I have a feeling it's impossible, but I'd like to know if there is a solution. I'd like to keep solely to HTML and JavaScript; no Flash please.
Strictly speaking, the answer is no. A developer cannot prevent a user from uploading files of any type or extension using front-end validation (HTML/JavaScript).But still, the accept attribute of <input type = "file"> can help to provide a filter in the file select dialog box provided by the user's browser/OS. For example,
<!-- (IE 10+, Edge (EdgeHTML), Edge (Chromium), Chrome, Firefox 42+) -->
<input type="file" accept=".xls,.xlsx" />
should provide a way to filter out files other than .xls or .xlsx. Although the MDN page for input element always said that it supports this, to my surprise, this didn't work for me in Firefox until version 42. This works in IE 10+, Edge, and Chrome.
So, for supporting Firefox older than 42 along with IE 10+, Edge, Chrome, and Opera, I guess it's better to use comma-separated list of MIME-types:
<!-- (IE 10+, Edge (EdgeHTML), Edge (Chromium), Chrome, Firefox) -->
<input type="file"
accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel" />
[Edge (EdgeHTML) behavior: The file type filter dropdown shows the file types mentioned here, but is not the default in the dropdown. The default filter is All files (*).]
You can also use asterisks in MIME-types. For example:
<input type="file" accept="image/*" /> <!-- all image types -->
<input type="file" accept="audio/*" /> <!-- all audio types -->
<input type="file" accept="video/*" /> <!-- all video types -->
W3C recommends authors to specify both MIME-types and their corresponding extensions in the accept attribute. So, the best approach is:
<!-- Right approach: Use both file extensions and their corresponding MIME-types. -->
<!-- (IE 10+, Edge (EdgeHTML), Edge (Chromium), Chrome, Firefox) -->
<input type="file"
accept=".xls,.xlsx, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel" />
JSFiddle of the same: here.
Reference: List of MIME-types
IMPORTANT: Using the accept attribute only provides a way of filtering in the files of types that are of interest. Browsers still allow users to choose files of any type. Additional (client-side) checks should be done (using JavaScript, one way would be this), and definitely file types MUST be verified on the server, using a combination of MIME-type using both the file extension and its binary signature (ASP.NET, PHP, Ruby, Java). You might also want to refer to these tables for file types and their magic numbers, to perform a more robust server-side verification.
Here are three good reads on file-uploads and security.
EDIT: Maybe file type verification using its binary signature can also be done on client side using JavaScript (rather than just by looking at the extension) using HTML5 File API, but still, the file must be verified on the server, because a malicious user will still be able to upload files by making a custom HTTP request.
There is the accept attribute for the input tag. However, it is not reliable in any way.
Browsers most likely treat it as a "suggestion", meaning the user will, depending on the file manager as well, have a pre-selection that only displays the desired types. They can still choose "all files" and upload any file they want.
For example:
<form>
<input type="file" name="pic" id="pic" accept="image/gif, image/jpeg" />
</form>
Read more in the HTML5 spec
Keep in mind that it is only to be used as a "help" for the user to find the right files.
Every user can send any request he/she wants to your server.
You always have to validated everything server-side.
So the answer is: no you cannot restrict, but you can set a pre-selection but you cannot rely on it.
Alternatively or additionally you can do something similar by checking the filename (value of the input field) with JavaScript, but this is nonsense because it provides no protection and also does not ease the selection for the user. It only potentially tricks a webmaster into thinking he/she is protected and opens a security hole. It can be a pain in the ass for users that have alternative file extensions (for example jpeg instead of jpg), uppercase, or no file extensions whatsoever (as is common on Linux systems).
You can use the change event to monitor what the user selects and notify them at that point that the file is not acceptable. It does not limit the actual list of files displayed, but it is the closest you can do client-side, besides the poorly supported accept attribute.
var file = document.getElementById('someId');
file.onchange = function(e) {
var ext = this.value.match(/\.([^\.]+)$/)[1];
switch (ext) {
case 'jpg':
case 'bmp':
case 'png':
case 'tif':
alert('Allowed');
break;
default:
alert('Not allowed');
this.value = '';
}
};
<input type="file" id="someId" />
JSFiddle
Yes, you are right. It's impossible with HTML. User will be able to pick whatever file he/she wants.
You could write a piece of JavaScript code to avoid submitting a file based on its extension. But keep in mind that this by no means will prevent a malicious user to submit any file he/she really wants to.
Something like:
function beforeSubmit()
{
var fname = document.getElementById("ifile").value;
// check if fname has the desired extension
if (fname hasDesiredExtension) {
return true;
} else {
return false;
}
}
HTML code:
<form method="post" onsubmit="return beforeSubmit();">
<input type="file" id="ifile" name="ifile"/>
</form>
Technically you can specify the accept attribute (alternative in html5) on the input element, but it's not properly supported.
You can use the "accept" attribute as a filter in the file select box.
Using "accept" help you filter input files based on their "suffix" or their "MIME type"
1.Filter based on suffix:
Here "accept" attribute just allow to select files with .jpeg extension.
<input type="file" accept=".jpeg" />
2.Filter based on "file type"
Here the "accept" attribute just allows you to select a file with "image/jpeg" type.
<input type="file" accept="image/jpeg" />
Important: We can change or delete the extension of a file, without changing the meme type. For example it is possible to have a file without extension, but the type of this file can be "image/jpeg". So this file can not pass the accept=".jpeg" filter. but it can pass accept="image/jpeg".
3.We can use * to select all kinds of file types. For example below code allows to select all kinds of images. for example "image/png" or "image/jpeg" or ... . All of them are allowed.
<input type="file" accept="image/*" />
4.We can use cama ( , ) as an "or operator" in the select attribute. For example to allow all kind of images or pdf files we can use this code:
<input type="file" accept="image/* , application/pdf" />
Use input tag with accept attribute
<input type="file" name="my-image" id="image" accept="image/gif, image/jpeg, image/png" />
Click here for the latest browser compatibility table
Live demo here
To select only image files, you can use this accept="image/*"
<input type="file" name="my-image" id="image" accept="image/*" />
Live demo here
Only gif, jpg and png will be shown, screen grab from Chrome version 44
I know this is a bit late.
function Validatebodypanelbumper(theForm)
{
var regexp;
var extension = theForm.FileUpload.value.substr(theForm.FileUpload1.value.lastIndexOf('.'));
if ((extension.toLowerCase() != ".gif") &&
(extension.toLowerCase() != ".jpg") &&
(extension != ""))
{
alert("The \"FileUpload\" field contains an unapproved filename.");
theForm.FileUpload1.focus();
return false;
}
return true;
}
You could actually do it with javascript but remember js is client side, so you would actually be "warning users" what type of files they can upload, if you want to AVOID (restrict or limit as you said) certain type of files you MUST do it server side.
Look at this basic tut if you would like to get started with server side validation. For the whole tutorial visit this page.
Good luck!
As mentioned in previous answers we cannot restrict user to select files for only given file formats. But it's really handy to use the accept tag on file attribute in html.
As for validation, we have to do it at the server side. We can also do it at client side in js but its not a foolproof solution. We must validate at server side.
For these requirements I really prefer struts2 Java web application development framework. With its built-in file upload feature, uploading files to struts2 based web apps is a piece of cake. Just mention the file formats that we would like to accept in our application and all the rest is taken care of by the core of framework itself. You can check it out at struts official site.
I may suggest following:
If you have to make user select any of image files by default, the use accept="image/*"
<input type="file" accept="image/*" />
if you want to restrict to specific image types then use accept="image/bmp, image/jpeg, image/png"
<input type="file" accept="image/bmp, image/jpeg, image/png" />
if you want to restrict to specific types then use accept=".bmp, .doc, .pdf"
<input type="file" accept=".bmp, .doc, .pdf" />
You cannot restrict user to change file filer to all files, so always validate file type in script and server
Building on the previous answers of using the accept attribute, you can accomplish this using the File API. This also gives you access to the file contents should you use FileReader to do some local parsing or data handling.
First create an input element, here you could apply the file type to the accept attribute but for the example it will allow you to select all file types.
<input type="file" name="upload" accept="*" multiple>
Next we need to listen to the 'change' event on the input element.
var upload = document.querySelector('input[type="file"]');
upload.addEventListener('change', function() {});
Inside the function you'll be able to access the files object of the input.
var files = this.files
We can't just iterate over the object since it isn't an array, however we can use the item() function to access our File object from the list.
for (var i = 0; i < files.length; i++) {
var file = files.item(i);
}
Now that we have our File object, we can access its name and type properties and do our file check here. In this case I'm checking to see if it's a .txt file and printing a message if it isn't. You can check the name against a regex pattern for the file type or check the type against its MIME type.
if (!file.name.match(/.txt$/i) || file.type != 'text/plain') {
console.log(file.name + ' is not a .txt file.');
}
var upload = document.querySelector('input[type="file"]');
upload.addEventListener('change', function() {
var files = this.files;
for (var i = 0; i < files.length; i++) {
var file = files.item(i);
if (!file.name.match(/.txt$/i) || file.type != 'text/plain') {
console.log(file.name + ' is not a .txt file.');
}
}
});
<input type="file" name="upload" accept="*" multiple>
File API is very well supported for modern browsers. By combining this with the accept attribute you can easily filter what the local user can select in an upload and provide useful feedback. If you are uploading the file, you should still check and validate the file type on your backend.