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

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

Related

When does browser read the file selected in input type=file

My HTML page has a <input type="file"/> element, and I do the following steps:
Click browse and select a file
Edit the file contents from disk
Click on form submit
What are the contents that are expected to go to the server in such case? Is there a definition in any spec as to what should happen (i.e the original contents should be sent, or the new contents should be sent) or is the implementation left to the browser?
This depends on how the file input is used. However, in the most general scenario, the file content is read at the upload time.
When you execute the submit action of a form, it will go through all its elements and compose an HTTP request with all the input data. It is at this specific time the physical file on the disk is read by the form action.
Now, there are other manipulations of form submission commonly done in web applications. The file content, for example, can be read immediately by the onChange event of the file input element and an application can store this data in a hidden element inside the form. It may be this data embedded in the hidden element that the server is really considering.
Your non-modified data will be submitted to the server in this scenario.
I just created a simple example and found that browser keep the reference to the uploaded file.
In the nutshell:
Create foo.txt file
Add 'Hello world' content
Save file
Upload the file by using <input type="file />
browser keeps reference to the selected file
Make some changes in the file. Change 'Hello world' to 'Hello world 2'
Press submit button
The file foo.txt with 'Hello world 2' will be submitted.
You can try to test this scenario by using snippet below. Upload the file and make some changes during setTimeout().
const input = document.querySelector('#input');
let cache = null;
function onFileChange(event) {
const [ file ] = event.target.files;
cache = file;
readFileData(file).then(result => {
console.log('Result:', result);
// Edit file during the timeout
setTimeout(() => {
console.log('File', cache);
}, 10000)
})
}
function readFileData(file) {
const reader = new FileReader(file);
return new Promise((resolve, reject) => {
reader.onload = event => resolve(event.target.result);
reader.onerror = error => reject(error)
reader.readAsText(file);
});
}
input.addEventListener('change', onFileChange);
<form>
<input id="input" type="file" />
</form>
Update:
Also it is possible to read data into the local variable after file has been uploaded. In such case, you will keep local copy of entire file and it will not be affected.

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>

HTML input tag file handling

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);

How to make input type= file Should accept only pdf and xls

I used <input type= "file" name="Upload" >
Now I would like to restrict this by accepting only .pdf and .xls files.
When I click the submit button it should validate this.
And when I click the files (PDF/XLS) on webpage it should automatically open.
Could anyone please give some examples for this?
You could do so by using the attribute accept and adding allowed mime-types to it. But not all browsers do respect that attribute and it could easily be removed via some code inspector. So in either case you need to check the file type on the server side (your second question).
Example:
<input type="file" name="upload" accept="application/pdf,application/vnd.ms-excel" />
To your third question "And when I click the files (PDF/XLS) on webpage it automatically should open.":
You can't achieve that. How a PDF or XLS is opened on the client machine is set by the user.
you can use this:
HTML
<input name="userfile" type="file" accept="application/pdf, application/vnd.ms-excel" />
support only .PDF and .XLS files
Unfortunately, there is no guaranteed way to do it at time of selection.
Some browsers support the accept attribute for input tags. This is a good start, but cannot be relied upon completely.
<input type="file" name="pic" id="pic" accept="image/gif, image/jpeg" />
You can use a cfinput and run a validation to check the file extension at submission, but not the mime-type. This is better, but still not fool-proof. Files on OSX often have no file extensions or users could maliciously mislabel the file types.
ColdFusion's cffile can check the mime-type using the contentType property of the result (cffile.contentType), but that can only be done after the upload. This is your best bet, but is still not 100% safe as mime-types could still be wrong.
You can try following way
<input type= "file" name="Upload" accept = "application/pdf,.csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel">
OR (in asp.net mvc)
#Html.TextBoxFor(x => x.FileName, new { #id = "doc", #type = "file", #accept = "application/pdf,.csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" })
You could use JavaScript. Take in consideration that the big problem with doing this with JavaScript is to reset the input file. Well, this restricts to only JPG (for PDF you will have to change the mime type and the magic number):
<form id="form-id">
<input type="file" id="input-id" accept="image/jpeg"/>
</form>
<script type="text/javascript">
$(function(){
$("#input-id").on('change', function(event) {
var file = event.target.files[0];
if(file.size>=2*1024*1024) {
alert("JPG images of maximum 2MB");
$("#form-id").get(0).reset(); //the tricky part is to "empty" the input file here I reset the form.
return;
}
if(!file.type.match('image/jp.*')) {
alert("only JPG images");
$("#form-id").get(0).reset(); //the tricky part is to "empty" the input file here I reset the form.
return;
}
var fileReader = new FileReader();
fileReader.onload = function(e) {
var int32View = new Uint8Array(e.target.result);
//verify the magic number
// for JPG is 0xFF 0xD8 0xFF 0xE0 (see https://en.wikipedia.org/wiki/List_of_file_signatures)
if(int32View.length>4 && int32View[0]==0xFF && int32View[1]==0xD8 && int32View[2]==0xFF && int32View[3]==0xE0) {
alert("ok!");
} else {
alert("only valid JPG images");
$("#form-id").get(0).reset(); //the tricky part is to "empty" the input file here I reset the form.
return;
}
};
fileReader.readAsArrayBuffer(file);
});
});
</script>
Take in consideration that this was tested on latest versions of Firefox and Chrome, and on IExplore 10.
For a complete list of mime types see Wikipedia.
For a complete list of magic number see Wikipedia.
I would filter the files server side, because there are tools, such as Live HTTP Headers on Firefox that would allow to upload any file, including a shell. People could hack your site. Do it server site, to be safe.
While this particular example is for a multiple file upload, it gives the general information one needs:
https://developer.mozilla.org/en-US/docs/DOM/File.type
As far as acting upon a file upon /download/ this is not a Javascript question -- but rather a server configuration. If a user does not have something installed to open PDF or XLS files, their only choice will be to download them.
If you want the file upload control to Limit the types of files user can upload on a button click then this is the way..
<script type="text/JavaScript">
<!-- Begin
function TestFileType( fileName, fileTypes ) {
if (!fileName) return;
dots = fileName.split(".")
//get the part AFTER the LAST period.
fileType = "." + dots[dots.length-1];
return (fileTypes.join(".").indexOf(fileType) != -1) ?
alert('That file is OK!') :
alert("Please only upload files that end in types: \n\n" + (fileTypes.join(" .")) + "\n\nPlease select a new file and try again.");
}
// -->
</script>
You can then call the function from an event like the onClick of the above button, which looks like:
onClick="TestFileType(this.form.uploadfile.value, ['gif', 'jpg', 'png', 'jpeg']);"
You can change this to: PDF and XLS
You can see it implemented over here: Demo
put your MIME type in the accept attribute
search for your file extension MIME type from here :
https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types
Try this one:-
<MyTextField
id="originalFileName"
type="file"
inputProps={{ accept: '.xlsx, .xls, .pdf' }}
required
label="Document"
name="originalFileName"
onChange={e => this.handleFileRead(e)}
size="small"
variant="standard"
/>

How to set name of file downloaded from browser?

I'm writing a web application that, among other things, allows users to upload files to my server. In order to prevent name clashes and to organize the files, I rename them once they are put on my server. By keeping track of the original file name I can communicate with the file's owner without them ever knowing I changed the file name on the back end. That is, until they go do download the file. In that case they're prompted to download a file with a unfamiliar name.
My question is, is there any way to specify the name of a file to be downloaded using just HTML? So a user uploads a file named 'abc.txt' and I rename it to 'xyz.txt', but when they download it I want the browser to save the file as 'abc.txt' by default. If this isn't possible with just HTML, is there any way to do it?
When they click a button to download the file, you can add the HTML5 attribute download where you can set the default filename.
That's what I did, when I created a xlsx file and the browser want to save it as zip file.
Download
Download Export
Can't find a way in HTML. I think you'll need a server-side script which will output a content-disposition header. In php this is done like this:
header('Content-Disposition: attachment; filename="downloaded.pdf"');
if you wish to provide a default filename, but not automatic download, this seems to work.
header('Content-Disposition: inline; filename="filetodownload.jpg"');
In fact, it is the server that is directly serving your files, so you have no way to interact with it from HTML, as HTML is not involved at all.
just need to use HTML5 a tag download attribute
codepen live demo
https://codepen.io/xgqfrms/full/GyEGzG/
my screen shortcut.
update answer
whether a file is downloadable depends on the server's response config, such as Content-Type, Content-Disposition;
download file's extensions are optional, depending on the server's config, too.
'Content-Type': 'application/octet-stream',
// it means unknown binary file,
// browsers usually don't execute it, or even ask if it should be executed.
'Content-Disposition': `attachment; filename=server_filename.filetype`,
// if the header specifies a filename,
// it takes priority over a filename specified in the download attribute.
download blob url file
function generatorBlobVideo(url, type, dom, link) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.responseType = 'arraybuffer';
xhr.onload = function(res) {
// console.log('res =', res);
var blob = new Blob(
[xhr.response],
{'type' : type},
);
// create blob url
var urlBlob = URL.createObjectURL(blob);
dom.src = urlBlob;
// download file using `a` tag
link.href = urlBlob;
};
xhr.send();
}
(function() {
var type = 'image/png';
var url = 'https://cdn.xgqfrms.xyz/logo/icon.png';
var dom = document.querySelector('#img');
var link = document.querySelector('#img-link');
generatorBlobVideo(url, type, dom, link);
})();
https://cdn.xgqfrms.xyz/HTML5/Blob/index.html
refs
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a#download
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition
https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types#important_mime_types_for_web_developers
Sometimes #Mephiztopheles answer won't work on blob storages and some browsers.
For this you need to use a custom function to convert the file to blob and download it
const coverntFiletoBlobAndDownload = async (file, name) => {
const blob = await fetch(file).then(r => r.blob())
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.style.display = 'none'
a.href = url
a.download = name // add custom extension here
document.body.appendChild(a)
a.click()
window.URL.revokeObjectURL(url)
}
Same code as #Hillkim Henry but with a.remove() improvement
This forces the document to remove the a tag from the body and avoid multiple elements
const coverntFiletoBlobAndDownload = async (file, name) => {
const blob = await fetch(file).then(r => r.blob())
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.style.display = 'none'
a.href = url
a.download = name // add custom extension here
document.body.appendChild(a)
a.click()
window.URL.revokeObjectURL(url)
// Remove "a" tag from the body
a.remove()
}
Well, #Palantir's answer is, for me, the most correct way!
If you plan to use that with multiple files, then i suggest you to use (or make one) PHP Download Manager.
BUT, if you want to make that to one or two files, I will suggest you the mod_rewrite option:
You have to create or edit your .htaccess file on htdocs folder and add this:
RewriteEngine on
RewriteRule ^abc\.txt$ xyz.txt
With this code, users will download xyz.txt data with the name abc.txt
NOTE: Verify if you have already the "RewriteEngine on " on your file, if yes, add only the second for each file you wish to redirect.
Good Luck ;)
(Sorry for my english)