HTML input tag file handling - html

In this code for the PDF reader pdf-js there is an input tag to let the user upload an input file
<input id="fileInput" class="fileInput" type="file" oncontextmenu="return false;" style="visibility: hidden; position: fixed; right: 0; top: 0" />
This input tag is not a part of any form. Once the user uploads the file, where does it go? Where is the code that processes the file? (I'm asking in general, not necessarily specific to this piece of code.)

"Then it's interesting. This code doesn't have server side"
No, It doesn't.
Pdf.js is a client side program that written with javascript. So that works on javascript side.
It actually takes the file that you wanna show, and does whatever must be done like converting the buffer to Uint8Array than renders it.
All processes happen on javascript side. No server side, no file upload.
Here is an article about reading local files in javascript
Here is the related part of code in pdf.viewer.js
window.addEventListener('change', function webViewerChange(evt) {
var files = evt.target.files;
if (!files || files.length === 0)
return;
// Read the local file into a Uint8Array.
var fileReader = new FileReader();
fileReader.onload = function webViewerChangeFileReaderOnload(evt) {
var buffer = evt.target.result;
var uint8Array = new Uint8Array(buffer);
PDFView.open(uint8Array, 0);
};
var file = files[0];
fileReader.readAsArrayBuffer(file);
PDFView.setTitleUsingUrl(file.name);
// URL does not reflect proper document location - hiding some icons.
document.getElementById('viewBookmark').setAttribute('hidden', 'true');
document.getElementById('download').setAttribute('hidden', 'true');
}, true);

Related

How to set value of an input with type of image file in HTML? [duplicate]

How can I set the value of this?
<input type="file" />
You cannot set it to a client side disk file system path, due to security reasons.
Imagine:
<form name="foo" method="post" enctype="multipart/form-data">
<input type="file" value="c:/passwords.txt">
</form>
<script>document.foo.submit();</script>
You don't want the websites you visit to be able to do this, do you? =)
You can only set it to a publicly accessible web resource as seen in this answer, but this is clearly not the same as a client side disk file system path and it's therefore useless in that context.
You can't.
The only way to set the value of a file input is by the user to select a file.
This is done for security reasons. Otherwise you would be able to create a JavaScript that automatically uploads a specific file from the client's computer.
Not an answer to your question (which others have answered), but if you want to have some edit functionality of an uploaded file field, what you probably want to do is:
show the current value of this field by just printing the filename or URL, a clickable link to download it, or if it's an image: just show it, possibly as thumbnail
the <input> tag to upload a new file
a checkbox that, when checked, deletes the currently uploaded file. note that there's no way to upload an 'empty' file, so you need something like this to clear out the field's value
You can't. And it's a security measure. Imagine if someone writes JS that sets file input value to some sensitive data file?
I have write full example for load URL to input file, and preview
you can check here
1
https://vulieumang.github.io/vuhocjs/file2input-input2file/
in short you can use this function
function loadURLToInputFiled(url){
getImgURL(url, (imgBlob)=>{
// Load img blob to input
// WIP: UTF8 character error
let fileName = 'hasFilename.jpg'
let file = new File([imgBlob], fileName,{type:"image/jpeg", lastModified:new Date().getTime()}, 'utf-8');
let container = new DataTransfer();
container.items.add(file);
document.querySelector('#file_input').files = container.files;
})
}
// xmlHTTP return blob respond
function getImgURL(url, callback){
var xhr = new XMLHttpRequest();
xhr.onload = function() {
callback(xhr.response);
};
xhr.open('GET', url);
xhr.responseType = 'blob';
xhr.send();
}
As everyone else here has stated: You cannot upload just any file automatically with JavaScript.
HOWEVER! If you have access to the information you want to send in your code (i.e., not C:\passwords.txt), then you can upload it as a blob-type, and then treat it as a file.
What the server will end up seeing will be indistinguishable from someone actually setting the value of <input type="file" />. The trick, ultimately, is to begin a new XMLHttpRequest() with the server...
function uploadFile (data) {
// define data and connections
var blob = new Blob([JSON.stringify(data)]);
var url = URL.createObjectURL(blob);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'myForm.php', true);
// define new form
var formData = new FormData();
formData.append('someUploadIdentifier', blob, 'someFileName.json');
// action after uploading happens
xhr.onload = function(e) {
console.log("File uploading completed!");
};
// do the uploading
console.log("File uploading started!");
xhr.send(formData);
}
// This data/text below is local to the JS script, so we are allowed to send it!
uploadFile({'hello!':'how are you?'});
So, what could you possibly use this for? I use it for uploading HTML5 canvas elements as jpg's. This saves the user the trouble of having to open a file input element, only to select the local, cached image that they just resized, modified, etc.. But it should work for any file type.
You need to create a DataTransfer and set the .files property of the input.
const dataTransfer = new DataTransfer();
dataTransfer.items.add(myFile);//your file(s) reference(s)
document.getElementById('input_field').files = dataTransfer.files;
the subject is very old but I think someone can need this answer!
<input type="file" />
<script>
// Get a reference to our file input
const fileInput = document.querySelector('input[type="file"]');
// Create a new File object
const myFile = new File(['Hello World!'], 'myFile.txt', {
type: 'text/plain',
lastModified: new Date(),
});
// Now let's create a DataTransfer to get a FileList
const dataTransfer = new DataTransfer();
dataTransfer.items.add(myFile);
fileInput.files = dataTransfer.files;
</script>
Define in html:
<input type="hidden" name="image" id="image"/>
In JS:
ajax.jsonRpc("/consulta/dni", 'call', {'document_number': document_number})
.then(function (data) {
if (data.error){
...;
}
else {
$('#image').val(data.image);
}
})
After:
<input type="hidden" name="image" id="image" value="/9j/4AAQSkZJRgABAgAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8U..."/>
<button type="submit">Submit</button>
Actually we can do it.
we can set the file value default by using webbrowser control in c# using FormToMultipartPostData Library.We have to download and include this Library in our project. Webbrowser enables the user to navigate Web pages inside form.
Once the web page loaded , the script inside the webBrowser1_DocumentCompleted will be executed.
So,
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
FormToMultipartPostData postData =
new FormToMultipartPostData(webBrowser1, form);
postData.SetFile("fileField", #"C:\windows\win.ini");
postData.Submit();
}
Refer the below link for downloading and complete reference.
https://www.codeproject.com/Articles/28917/Setting-a-file-to-upload-inside-the-WebBrowser-com

NodeJS load a json from a file selector without reloading webpage

Has anyone done this?
I need to be able to grab a JSON file from a input file selector from HTML, after that read it, parse it and show it in the webpage.
The page cannot reload and I don't need to upload/copy it to any of my folders. I just need to read it and show it without reloading the webpage.
Any ideas? I'm on Nodejs. I'm serving static html pages. Apparently it's simple but I'm struggling a lot.
HTML:
<input type="file" onchange='getContent(this)' />
<div id="file-content"></div>
JS:
function getContent(content) {
if (content.files && content.files[0]) {
var contentReader = new FileReader();
contentReader.onload = function(e) {
var output = e.target.result;
document.getElementById('file-content').innerHTML = output;
};
contentReader.readAsText(content.files[0]);
}
}
You can see live preview here

Import csv file to handsontable

I'm looking for import data from a csv file to a handsontable. I only found answers to export in csv but I don't want to.
Any idea please !
I've developed some javaScript code that will upload xml to handsontable. You may be able to adapt this:
Use an XMLHttpRequest to upload a file (this would be from local machine) something like this:
function uploadFile()
{
var url = $("#fileUpload").val(); //gets filename from html input field
var xhr = (window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP"));
xhr.onreadystatechange = XHRhandler;
xhr.open("GET", url, true);
xhr.send(null);
function XHRhandler() {
if (xhr.readyState == 4) {
//the raw text from the file
var rawText = xhr.responseText;
xhr = null;
makeDataArray(); //Make a function that uses the rawText
//and parse out an array for the data portion of the table.
makeTable(); //Make a function that renders the table with the data
}
}
}
Be sure that all of the things you do to get the data from the xhr call is in that loop otherwise you'll have an empty variable (due to the asynchronous nature of the call).
Use some of this html code to add in the file box:
<input type="text" id="fileUpload" value="file.csvX"/> </input>
<input id="upload" type="button" value="Upload" onclick="uploadFile();"/> </input>

<input type="file"> limit selectable files by extensions [duplicate]

This question already has answers here:
Limit file format when using <input type="file">?
(12 answers)
Closed 7 years ago.
How can someone limit the files that can be selected with the input type="file" element by extensions?
I already know the accept attribute, but in chrome it does limit the files by the last MIME Type defined (in this case "gif") and FF4 does not even limit anything.
<input type="file" accept="image/jpg, image/gif">
Am I doing anything wrong or is there another way?
Easy way of doing it would be:
<input type="file" accept=".gif,.jpg,.jpeg,.png,.doc,.docx">
Works with all browsers, except IE9. I haven't tested it in IE10+.
NOTE: This answer is from 2011. It was a really good answer back then, but as of 2015, native HTML properties are supported by most browsers, so there's (usually) no need to implement such custom logic in JS. See Edi's answer and the docs.
Before the file is uploaded, you can check the file's extension using Javascript, and prevent the form being submitted if it doesn't match. The name of the file to be uploaded is stored in the "value" field of the form element.
Here's a simple example that only allows files that end in ".gif" to be uploaded:
<script type="text/javascript">
function checkFile() {
var fileElement = document.getElementById("uploadFile");
var fileExtension = "";
if (fileElement.value.lastIndexOf(".") > 0) {
fileExtension = fileElement.value.substring(fileElement.value.lastIndexOf(".") + 1, fileElement.value.length);
}
if (fileExtension.toLowerCase() == "gif") {
return true;
}
else {
alert("You must select a GIF file for upload");
return false;
}
}
</script>
<form action="upload.aspx" enctype="multipart/form-data" onsubmit="return checkFile();">
<input name="uploadFile" id="uploadFile" type="file" />
<input type="submit" />
</form>
However, this method is not foolproof. Sean Haddy is correct that you always want to check on the server side, because users can defeat your Javascript checking by turning off javascript, or editing your code after it arrives in their browser. Definitely check server-side in addition to the client-side check. Also I recommend checking for size server-side too, so that users don't crash your server with a 2 GB file (there's no way that I know of to check file size on the client side without using Flash or a Java applet or something).
However, checking client side before hand using the method I've given here is still useful, because it can prevent mistakes and is a minor deterrent to non-serious mischief.
Honestly, the best way to limit files is on the server side. People can spoof file type on the client so taking in the full file name at server transfer time, parsing out the file type, and then returning a message is usually the best bet.
function uploadFile() {
var fileElement = document.getElementById("fileToUpload");
var fileExtension = "";
if (fileElement.value.lastIndexOf(".") > 0) {
fileExtension = fileElement.value.substring(fileElement.value.lastIndexOf(".") + 1, fileElement.value.length);
}
if (fileExtension == "odx-d"||fileExtension == "odx"||fileExtension == "pdx"||fileExtension == "cmo"||fileExtension == "xml") {
var fd = new FormData();
fd.append("fileToUpload", document.getElementById('fileToUpload').files[0]);
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener("progress", uploadProgress, false);
xhr.addEventListener("load", uploadComplete, false);
xhr.addEventListener("error", uploadFailed, false);
xhr.addEventListener("abort", uploadCanceled, false);
xhr.open("POST", "/post_uploadReq");
xhr.send(fd);
}
else {
alert("You must select a valid odx,pdx,xml or cmo file for upload");
return false;
}
}
tried this , works very well

Can HTML 5 drag-and-drop handle folders?

I'm impressed by Gmail's ability to let you drag files into emails for attachments, but when I try to drag a folder onto it, it says the file has 0 bytes. Is this a Gmail limitation, or is this something that's fundamentally not doable with the current HTML 5 spec?
Now directory upload available on chrome
you can select directory using input type
<input type='file' webkitdirectory >
and you can drag drop a folder
<div id="dropzone"></div>
var dropzone = document.getElementById('dropzone');
dropzone.ondrop = function(e) {
var length = e.dataTransfer.items.length;
for (var i = 0; i < length; i++) {
var entry = e.dataTransfer.items[i].webkitGetAsEntry();
if (entry.isFile) {
... // do whatever you want
} else if (entry.isDirectory) {
... // do whatever you want
}
}
};
The current draft of html5 only supports a file list object for handling the
getData events. so you can drag multiple files to a drag target but no folders