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
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
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 can I save the modified data to the same xml file after loading from that external xml file in ActionScript3.
Is there exist any function or method or any way to save the modified data again in the same file from which it was loaded.
import flash.net.URLRequest;
var myXML:XML = new XML();
var XML_URL:String = "sample.xml";
var myXMLURL:URLRequest = new URLRequest(XML_URL);
var myLoader:URLLoader = new URLLoader(myXMLURL);
myLoader.addEventListener("complete", xmlLoaded);
function xmlLoaded(event:Event):void
{
myXML = XML(myLoader.data);
trace("Data loaded.");
trace(myXML); //showing output of just loaded xml file.
//process of adding new child node or property.
var newnode:XML = new XML();
newnode =
<student >
<sname srno="2">mm</sname>
<father tax="no">
<fname>Ratan</fname>
<focc>business man</focc>
<mobno>9928946899</mobno>
</father>
</student>;
myXML = myXML.appendChild(newnode);
trace(myXML); //showing o/p after being the child-node appended.
}
where the sample.xml file located in the same working path, contains only the following data.-
<data>
<student srno="1" class="5" rollno="1">
<sname>Rohan Jain</sname>
<father tax="yes">
<fname>Ronak Jain</fname>
<focc>teacher</focc>
<mobno>9928946899</mobno>
</father>
</student>
</data>
If you're building a browser based application; nothing you can do on the client will save the file to a specific name and location. You'll have to send your updated doc to the server for saving. It is easy to write a service to do this in most server side languages I have dealt with.
If you want to save the file to the client machine; you can do so using FileReference.save(). However, this requires user input and there is no way to guarantee what the user will name the file or where they'll put it.
I'm using the Dojo 1.6 dojox.form.Uploader in IE. This uses the dojox.form.uploader.plugins.Flash plugin to do the upload. In Firefox, HTML5 is used and I can submit other form data along with the uploads by calling:
uploaderDijit.upload({paramName:"paramValue"});
But in IE, the Flash version's upload function does not take the formData argument. Is there any way I can submit other data along with the file uploads using the Flash plugin?
Here is my sample code:
dojo.require("dojox.form.Uploader");
dojo.require("dojox.form.uploader.FileList");
dojo.require("dojox.form.uploader.plugins.Flash");
function doUpload(){
dijit.byId("uploader").upload({param: "paramValue"});
}
function onload(){
// create uploader & file list dijits
var uploaderDijit = new dojox.form.Uploader({
id: "uploader",
url: "MyApp/MyServlet",
multiple: true
});
var fileListDijit = new dojox.form.uploader.FileList({uploader:uploaderDijit});
// insert dijits into html
var formNode = dojo.byId("multiUploadForm");
var uploaderDiv = document.createElement("div");
formNode.appendChild(uploaderDiv);
uploaderDiv.appendChild(uploaderDijit.domNode);
uploaderDiv.appendChild(fileListDijit.domNode);
}
dojo.addOnLoad(onload);
And:
<form id="multiUploadForm" method="post" enctype="multipart/form-data" encoding="multipart/form-data"></form>
<button onclick="javascript:doUpload();">Upload</button>
I have tried adding an input node into the form:
<form id="multiUploadForm" method="post" enctype="multipart/form-data" encoding="multipart/form-data">
<input type="hidden" name="param" value="paramValue"/>
</form>
And I've also tried appending the parameter to the url, but no dice:
var uploaderDijit = new dojox.form.Uploader({
id: "uploader",
url: "MyApp/MyServlet?param=paramValue",
multiple: true
});
I believe something else is wrong.. Following is (allthough from 1.7.2 src) the function called which you state is your entrypoint in first code block. with 100% certainty, your GET parameter should be set if you use url: "MyApp/MyServlet?param=paramValue"
.
uploadFlash: function(/*Object ? */formData){
// summary:
// Uploads selected files. Alias "upload()" should be used instead.
// tags:
// private
this.onBegin(this.getFileList());
formData.returnType = "F";
this.flashMovie.doUpload(formData);
},