How do I get the contents of a file form a HTML form? Here is an example of what I'm working with. All it does it output something like "C:\Fake Path\nameoffile
<html>
<head>
<script type="text/javascript">
function doSomething(){
var fileContents = document.getElementById('idexample').value;
document.getElementById('outputDiv').innerHTML = fileContents;
}
</script>
</head>
<body >
<form name = "form_input" enctype="multipart/form-data">
<input type="file" name="whocares" id="idexample" />
<button type="button" onclick="doSomething()">Enter</button>
</form>
<div id="outputDiv"></div>
</body>
</html>
EDIT:
It seems the solution is difficult to implement this way. What I'm trying to accomplish is sending a file to a python script on my webserver. This is my first time trying this sort of thing so suggestions are welcome. I supposes I could put the python script in my cgi folder and pass the values to it using something like...
/cgi/pythonscript.py?FILE_OBJECT=fileobjecthere&OTHER_VARIABLES=whatever
Would this be a better solution for sending file content to a webserver rather than having javacript open it directly using FileReader?
You can actually do that with the new FileReader Object.
Try this working example
function doSomething()
{
var file = document.getElementById('idexample');
if(file.files.length)
{
var reader = new FileReader();
reader.onload = function(e)
{
document.getElementById('outputDiv').innerHTML = e.target.result;
};
reader.readAsBinaryString(file.files[0]);
}
}
(works with the newest versions of Chrome and Firefox)
yes. Replace line of input as given below, Then it will work :)
<input type="file" ACCEPT="text/html" name="whocares" id="idexample" />
You cannot get the contents of a file in a form without submitting the form to your server.
Related
I tried the below code to open excel file using javascript.
I tried in IE, Chrome, and Firefox but it's not opening the file.
<html>
<body>
<form name="form1">
<input type=button onClick="test()" value="Open File">
<br><br>
</form>
<script type="text/javascript">
function test() {
var Excel = new ActiveXObject("Excel.Application");
Excel.Visible = true;
Excel.Workbooks.Open("teste.xlsx");
}
</script>
</body>
</html>
Thanks in Advance!
Try using Absolute Path of the file you are trying to open
eg:
Excel.Workbooks.Open("E:\\test.xlsx");
ActiveXObject is only supported by IE, other browsers don't support it.
Excel.Workbooks.Open("teste.xlsx");
There is no path specified for teste.xlsx, provide appropriate file path. The file should be accessed by the browser in the client system, so path should be set accordingly like C:\\Temp\\teste.xlsx (something similar with appropriate system drive).
To upload a local file to Google Drive, I have an HTML <form></form> (see code below) that displays in a modal overtop a Google Sheet the user has open. The HTML form has <input type="file" name="..."> in it, and when I click to send the form object, I successfully upload the file if this Google Apps Script is "bound" to a specific Sheets file (and was written using the Tools > Script Editor... menu).
If I save the script as a standalone script and then test it (installed and enabled) on a Sheets file of my choosing, then the <form>'s onclick action and the attempt to call google.script.run.aServerFunction(...) causes a "NetworkError: Connection failure due to HTTP 403". To clarify this is what I mean by creating a standalone script and testing it on a Sheets file: https://developers.google.com/apps-script/add-ons/#understand_the_development_cycle. In earlier code iterations I alternatively got a authorization scriptError of some kind. Same error when script is published privately for testers to use on a Sheet. Unfortunately, I think I need this as a standalone script that is later publishable as an add-on- not a side script bound to a single Sheet using the Tools > Script Editor... menu.
My first post to Stack Overflow- please forgive any jargon or typography mistakes, and thank you!
HTML adapted from tutorials:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<script>
function failed(event) {
$("div.response").text(event);
//google.script.run.selectStuff();
//google.script.host.close();
}
</script>
</head>
<body>
<form id="myForm">
<label>Your Name</label>
<input type="text" name="myName">
<label>Pick a file</label>
<input type="file" name="myFile">
<input type="submit" value="Upload File"
onclick="google.script.run.withFailureHandler(failed)
.uploadFiles(this.parentNode);
return false;">
</form>
<div class="response"></div>
</body>
</html>
In the code.gs:
function uploadFiles(formObject) {
/*var sheet1 = SpreadsheetApp.getActiveSheet();
sheet1.setActiveRange(sheet1.getRange(2, 2, 4, 4));
var formBlob = formObject.myFile;
var driveFile = DriveApp.createFile(formBlob);
driveFile.addEditor("...");
SpreadsheetApp.getActive().toast(driveFile.getUrl());
sheet1.getRange(1,1,1,1).setValue(driveFile.getUrl());
return driveFile.getUrl();*/
return "it worked";
}
I believe the reason you are getting the HTTP 403 error is because form DOM elements are illegal arguments in google.script.run.myfunction(...) in sheet addons. Even though they are mentioned here as legal parameters here, I think add-on have the added restriction of not being able to pass any kind of DOM elements.
The solution I came up with is to convert the uploaded file to base64 encode string using Filereader.readAsDataUrl() function in native javascript and passing the string to google script and converting it back to a file to be uploaded into google drive.
The base64 encode string starts like this:
data:application/pdf;base64,JVBERi0xLjMKJcTl8uXrp/Og0MTG....
GAS
function uploadFiles(formObject) {
// extract contentType from the encoded string
var contentType = formObject.split(",")[0].split(";")[0].split(":")[1]
// New Blob(data,contentType,name)
// Use base64decode to get file data
var blob = Utilities.newBlob(Utilities.base64Decode(formObject.split(",")[1]), contentType, "trial")
var driveFile = DriveApp.getFolderById("your Folder ID here").createFile(blob);
//return contentType, can be anything you like
return blob.getContentType()
}
HTML script
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
</head>
<body>
<form id="myForm">
<label>Your Name</label>
<input type="text" name="myName">
<label>Pick a file</label>
<input type="file" id = "filemy" name="myFile">
<input type="button" value="Upload File"
onclick="upload(this.parentNode)">
</form>
<div class="response"></div>
</body>
<script>
function failed(event) {
$("div.response").text(event);
//google.script.run.selectStuff();
//google.script.host.close();
}
function upload(frmData){
var file = document.getElementById("filemy").files[0]
var reader = new FileReader()
//reader.onload is triggered when readAsDataURL is has finished encoding
//This will take a bit of time, so be patient
reader.onload = function(event) {
// The file's text will be printed here
console.log("File being Uploaded")
//console.log(event.target.result)
google.script.run.withFailureHandler(failed).withSuccessHandler(failed)
.uploadFiles(event.target.result);
};
reader.readAsDataURL(file);
console.log(reader.result)
}
</script>
</html>
Final notes: I have not extensively tested the code, I have got it to work with a pdf file and an image/png file with a Maximun size of 2.6MB. So please try these 2 file types out before going on to further types of file!
Also, files do take a while to upload so be patient(~5-10sec). Especially since there is no progress bar to show the upload progress, it feels like nothing is happening.
Hope that helps!
I have a problem trying to get the file path on chrome. This is my code with a javascript function:
<html>
<head>
<script language="javascript" type="text/javascript">
function getPath() {
var inputName = document.getElementById('ctrl');
var imgPath;
imgPath = inputName.value;
//alert(imgPath);
var x = document.createElement("INPUT");
x.setAttribute("type", "text");
x.setAttribute("value", imgPath);
document.body.appendChild(x);
}
</script>
</head>
<body>
<input type="file" name ="file1" id="ctrl" webkitdirectory directory multiple/>
<input type="submit" value="Enviar" onclick="getPath()"/>
</body>
</html>
when I press the button, the textfield show me this
C:\fakepath\ART.pdf
I tried to edit the internet explorer settings and it works fine, but I cant get the full path on chrome
Its any way to get the full path on chrome? Thanks
You are using the multiple and directory options so your paths will be avaible under inputName.files
For security reasons these will be relative paths. If you wish to read the files you need to use the FileReader API.
https://developer.mozilla.org/en-US/docs/Web/API/FileReader
I read in the comments that you are trying to save a file to a specific location. This can't be achieved through a browser. You just need to provide the file to be downloaded and the user will decide where to save it. Usually, it will be saved to the OS's default download folder.
Attempting to load file(s) into CKEditor 4 textarea using input button and javascript. The files contain simple HTML code and have extensions .inc and .txt
What I have works, BUT ONLY after using browser back/forward buttons (which a student discovered by mistake). Using the input loads file from local drive, textarea goes blank but the loaded file only appears after using browser back/forward buttons?
Here is the HTML we are using:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://cdn.ckeditor.com/4.5.11/standard/ckeditor.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
</head>
<body>
<textarea name="editor1" id="editor1" rows="10" cols="80">
Placeholder text...
</textarea>
<script>
CKEDITOR.replace( 'editor1' );
</script>
<input name="file" type="file" id="files" class="form-control" value="">
<script type="text/javascript">
function readTextFile(file, callback, encoding) {
var reader = new FileReader();
reader.addEventListener('load', function (e) {
callback(this.result);
});
if (encoding) reader.readAsText(file, encoding);
else reader.readAsText(file);
}
function fileChosen(input, output) {
if (input.files && input.files[0]) {
readTextFile(
input.files[0],
function (str) {
output.value = str;
}
);
}
}
$('#files').on('change', function () {
var result = $("#files").text();
//added this below testing
fileChosen(this, document.getElementById('editor1'));
CKEDITOR.instances['editor1'].setData(result);
});
</script>
</body>
</html>
Also placed on JSFiddle
and W3schools
FYI: The browser back/forward mystery does not work on above two sites, only when I am using local or on a server.
After 3 days of trying to solve this in classroom, I come here asking for input. We have spent hours trying different methods found here and numerous sites.
Security is not an issue on input file restrictions, only using in classroom for training purposes/examples.
Anyone?
Okay, I managed to make it work.
In order to replace the text, you need to call the setData(str); method on the CKEDITOR instance, not over the DOM element. You also need to tell the editor to update ("redraw") its contents.
So:
fileChosen
function fileChosen(input, output) {
if ( input.files && input.files[0] ) {
readTextFile(
input.files[0],
function (str) {
output.setData(str); // We use the setData() method
output.updateElement(); // Then we tell the CKEditor instance to update itself
}
);
}
}
File input change
$('#files').on('change', function () {
var result = $("#files").text();
fileChosen(this, CKEDITOR.instances.editor1); // We pass the CKEDITOR instance, not the DOM element
});
I also made the changes like importing jQuery before the CKEDITOR javascript file.
Check the results in this fiddle
i have an object element in my html body to show an Active reports which exports to a .pdf file. I need to use javascript to automatically print the pdf out to the client's default printer and then save the pdf to the server:
<script language="javascript" type="text/javascript">
// <!CDATA[
function PrintPDF() {
pdf.click();
pdf.setActive();
pdf.focus();
pdf.PrintAll();
}
// ]]>
....
<body onload="return PrintPDF();">
<form id="form1" runat="server">
<object id="pdfDoc" type="application/pdf" width="100%" height="100%" data="test.aspx?PrintReport=yes&SavePDF=yes"/>
</form>
</body>
With the data hard-code in the object tag, everything run without a problem.
The problem now is that I need to pass querystring to this page dynamically. I tried to set the attribute data in the javsacript to pass the querystring. The querystring value passed successfully, but the data attribute does not seem to be set. I get a blank page.
pdf.setAttribute("data","test.aspx?PrintReport=yes&SavePDF=yes&AccNum="+AccNum);
Does anyone have a clue how I can set the data attribute dynamically to pass in querystring?
Thanks,
var pdfObj = document.getElementById('pdfDoc');
pdfObj.data="test.aspx?PrintReport=yes&SavePDF=yes&AccNum="+AccNum;
As far as the data attribute you're doing everything fine. Here are some examples:
http://jsfiddle.net/3SxRu/
I think your problem might be more to do with the order of execution. What does your actual code look like? Are you writing over the body onLoad function or something?
Also, I assume using the data attribute is a requirement. HTML5 defines data-*. This attribute isn't really valid. Again, maybe your system requires it.
I suspect that things are happening out of order. Try waiting until the onload event of the window before adding the embed.
Also, I suggest using a script like PDFObject to handle the embedding since it is a reliable way to embed PDF across all the various browsers out there. For example you might have something like the following:
<html>
<head>
<title>PDFObject example</title>
<script type="text/javascript" src="pdfobject.js"></script>
<script type="text/javascript">
window.onload = function (){
// First build the link to the PDF raw data ("bits")
// getQueryStrings assumes something like http://stackoverflow.com/questions/2907482/how-to-get-the-query-string-by-javascript
var queryStrings = getQueryStrings();
var reportNameParamValue = queryStrings["reportName"];
var pdfBitsUrl = "getReportPdfBits.aspx?reportName=" + reportNameParamValue;
// just in case PDF cannot be embedded, we'll fix the fallback link below:
var pdfFallbackLink = document.getElementById("pdfFallbackAnchor");
pdfFallbackLink.href = pdfFallbackLink;
// now perform the actual embed using PDFObject script from http://pdfobject.com
var success = new PDFObject( {
url: pdfBitsUrl;
}).embed();
};
</script>
</head>
<body>
<p>It appears you don't have Adobe Reader or PDF support in this web
browser. <a id="pdfFallbackAnchor" href="sample.pdf">Click here to download the PDF</a></p>
</body>