Reading contents of an uploaded file - javascript

I have a JSP page, where an editor (ACE editor) is based on a DIV tag.
1. User upload a file (ex: my.txt)
2. This file is saved in the servlet (WEB-INF/my.txt)
Now, I want to open this file, copy it's contents to a variable in Java Script and populate the DIV tag.
How do I do this?
Based on an answer below, I've understood that once I get the contents of the file I can populate my DIV tag by using
var MyDiv1 = document.getElementById('DIV1');
MyDiv1.innerHTML = yourFileContent;
This solves the second part of the problem, now how to I open that file and copy its contents to a var in JS?
====================================EDIT==========================================
From the answers below, I've done the following steps
Step1: Getting the file contents, I take 4 input files so I've included a file counter to identify which file is being uploaded and when the 4th inpiut file is uploaded its contents are being stored to a string variable.
Servlet.java
response.setContentType("text/html");
String LINE = "<br>";
String filename = "/WEB-INF/myfile.txt";
fileTxt = "";
ServletContext context = getServletContext();
InputStream is = context.getResourceAsStream(filename);
if (is != null)
{
InputStreamReader isr = new InputStreamReader(is);
BufferedReader reader = new BufferedReader(isr);
PrintWriter writer = response.getWriter();
String text = "";
while ((text = reader.readLine()) != null) {
fileTxt = text + LINE;
writer.print(fileTxt);
HttpSession session = request.getSession(true);
session.setAttribute("FileText", "fileTxt");
}
}
Step2 : Submitting the forms for upload and right after submitting accessing the variable to populate ,
my.jsp
document.myform.submit();
var name = '<%= session.getAttribute("FileText") %>';
var div = document.getElementById("editor");
div.innerHTML = name;
PS: This still displays a null value, working on it and waiting fr answers.

Related

Change segment text before processing using hls.js

so due to some security reason i want to add some extra text to .ts file in the begining of so when parsing it causes buffering issues
to fix this i decided to removed that 'extra' text i added before processing the segment issue is i dont know how to manipulate arraybuffer so i can remove that text since i am not that knowledgable on js
I tried many things including just download hlsjs file directly then edit readystatechange
// >= HEADERS_RECEIVED
if (readyState >= 2) {
....
if (isArrayBuffer)
{
console.log(xhr.response);
var ress = xhr.response;
//console.log(ress.replace('FFmpeg',''));
var enc = new TextDecoder('ASCII');
var seg = enc.decode(ress);
//var binaryArray = new Uint8Array(this.response.slice(0)); // use UInt8Array for binary
//var blob = new Blob([seg], { type: "video/MP2T" });
var enc = new TextEncoder(); // always utf-8
var newww = enc.encode(enc.encode(seg));
var ddd = newww.buffer;
console.debug( newww );
console.debug( newww.buffer);
//dec = dec.replace('ÿØÿà �JFIF','') ;
//xhr.response = Array.from(newww) ;
data = ddd;
len = data.byteLength;
the idea was to convert arraybuffer to string remove that text then convert it back to arraybuffer

How do I set Acrobat XI printer settings through excel vba?

I am designing a vba code that allows users to input a set of technical drawing numbers and create a packet from it. I have run into a problem when dealing with autocad files. Because our company has AutoCAD LT I am unable to utilize the api, thus I am using adobe's PDFMaker api to convert the files directly to pdf. Unfortunately the settings for pdfMaker are rather limited so I need to parse through the outputted pdf packet and print it in black and white (monochrome). I currently have a subroutine that opens the packet and prints the necessary pages, however, it only prints black and white if I specifically open up acrobat and select my "Monochrome" configuration in the advanced settings. Is there a way to send the command (I believe it's in javascript?) to set this color configuration and set the size option to fit? Here is my code.
Public xlBook As Workbook
Public xlSheet As Worksheet
Public LastRow As Integer
Public ItemNumber As String
Public Vin5 As String
Public Vin As String
Public FullPath As String
Sub PdfFormat()
Dim strMakeFile As String
Dim LastRow As Integer
Set xlBook = ActiveWorkbook
Set xlSheet = xlBook.Sheets(1)
ItemNumber = Range("E1")
Vin5 = Range("F1")
Vin = ItemNumber & "0" & Vin5
FullPath = "\\eastfile\Departments\Engineering\MACROS\New Packet Output\" & Vin & "\"
strMakeFile = FullPath & Vin & ".pdf"
LastRow = Range("A" & xlSheet.Rows.Count).End(-4162).Row
Dim AcroExchApp As New Acrobat.AcroApp
Dim AcroExchAVDoc As New Acrobat.AcroAVDoc
Dim AcroExchPDDoc As Acrobat.AcroPDDoc
Dim OpenError As Boolean
Dim PrintError As Boolean
OpenError = AcroExchAVDoc.Open(strMakeFile, "")
!!!!!CODE FOR PRINTER SETTINGS HERE!!!!!
PrintError = AcroExchAVDoc.PrintPagesSilentEx(0, 5, 3, 1, 1, 0, 0, 0, -5)
Debug.Print "Open Error: " & Not (OpenError)
Debug.Print "Print Error: " & Not (PrintError)
Debug.Print Vin
AcroExchApp.CloseAllDocs
End Sub
Thank you for your time
The print parameters in Acrobat you can find in the Acro-js helpfile for example here: Acro JS setting print options
With VBS/VBA there are 2 ways to use it. With the help of Acro-Form API you can execute js-code more or less direkt. Here I gave a simple example: Execute Acro js from VBA/VBS
The other way is to use the JS-Object, which lets you use transformed js-code via VBA/VBS Ole connection. That's documented in the Adobe Acrobat IAC Reference.
How that works you can see in the following example, where I use jso for setting some print parameters. Change the given print parameters to that what you need or search in the Acro JS helfile for some other example and execute it via above described way direct. Good luck, Reinhard
'// print dropped files with printParameter
set WshShell = CreateObject ("Wscript.Shell")
set fs = CreateObject("Scripting.FileSystemObject")
Set objArgs = WScript.Arguments
if objArgs.Count < 1 then
msgbox("Please drag a file on the script")
WScript.quit
end if
'contact Acrobat
Set gApp = CreateObject("AcroExch.App")
gApp.show 'comment or take out to work in hidden mode
'open via Avdoc and print
for i=0 to objArgs.Count - 1
FileIn = ObjArgs(i)
Set AVDoc = CreateObject("AcroExch.AVDoc")
If AVDoc.Open(FileIn, "") Then
Set PDDoc = AVDoc.GetPDDoc()
Set JSO = PDDoc.GetJSObject
jso.print false, 0, 0, true
set pp = jso.getPrintParams
pp.printerName = "hp deskjet 990c"
pp.firstPage = 0 '-> Zero based (firstPage = 0)
pp.lastPage = 5 '-> Zero based (pageCount - 1)
pp.interactive = pp.constants.interactionLevel.automatic '-> no print dialog
pp.pageHandling = pp.constants.handling.booklet
pp.booklet.duplexMode = pp.constants.bookletDuplexModes.BothSides
pp.booklet.binding = pp.constants.bookletBindings.LeftTall
jso.print(pp)
gApp.CloseAllDocs
end if
next
gApp.hide
gApp.exit
MsgBox "Done!"
Quit()
Sub Quit()
Set JSO = Nothing
Set PDDoc = Nothing
Set gApp = Nothing
Wscript.quit
End Sub

Google Scripts: Pull Google Document Based on User ID / Email

Good Morning Stack!
I was looking for some advice for some expanded functionality on a Google Script that helps me track and process absence requests. The process is as follows:
A user submits their form responses
The form responses are stored on a spreadsheet
A google doc, pre-created, is pulled and the values from the spreadsheet are implanted in the document.
The document is converted to a PDF
That PDF is automatically emailed to me.
However, some work policies have changed and I now need this form to have a signature that is unique to the person filling the form. In the past we simply printed the resulting PDF and had the person sign off on it.
I know I do not have the technicality to add on any sort of Electronic Signature functionality, nor is emailing that PDF to them an option as it doesn't create a fillable PDF (and my users don't really know how to digitally sign items anyways)
So what I was thinking is to create a form unique to each of the 15-20 users of this process and instead of a getFileByID, have the script check the Google Users account / email and pull the file created for them and stored in my drive instead.
As follows is my current, functional, script. How could I make this work?
function onFormSubmit(e) {
var Last_Name = e.values[2];
var First_Name = e.values[3];
var Middle_Initial = e.values[4];
var Work_Location = e.values[5];
var Job_Title = e.values[6];
var Contact_Number = e.values[7];
var Start = e.values[8];
var End = e.values[9];
var Time = e.values[10];
var Reason = e.values[11];
var D = new Date();
var copyId = DriveApp
.getFileById("1sdfjlsdf55asdfnk565enasdfnsnsd2")
.makeCopy("AbsenceRequest" + Last_Name + Start).getId();
var copyDoc = DocumentApp.openById(copyId)
var copyBody = copyDoc.getActiveSection();
copyBody.replaceText('keyLastName', Last_Name);
copyBody.replaceText('keyFirstName', First_Name);
copyBody.replaceText('keyMiddleInitial', Middle_Initial);
copyBody.replaceText('keyWorkLocation', Work_Location);
copyBody.replaceText('keyJobTitle', Job_Title);
copyBody.replaceText('keyContactNumber',Contact_Number);
copyBody.replaceText('keyStart', Start);
copyBody.replaceText('keyEnd', End);
copyBody.replaceText('keyTime', Time);
copyBody.replaceText('keyDate', D);
copyDoc.saveAndClose();
var pdf = DriveApp.getFileById(copyId).getAs("application/pdf");
var Email = "email#email.org" + "," + "email#email.org";
var Subject = "Absence Request"
var Body = "This is an absence request"
MailApp.sendEmail(Email, Subject, Body, {attachments: pdf});
DriveApp.getFileById(copyId).setTrashed(true);
}

pass xml from jsp to javascript

So I have a JSP file which gets an xml file from the session:
<%
org.w3c.dom.Document list = (org.w3c.dom.Document) session.getAttribute("list");
%>
<script type="text/javascript">
var list = <%=list %>
</script>
And I want to use it in javascript but I can't seem to find a way to load an XML file without providing an URL. The XML file is stored in a database so providing an URL is not possible. Does anyone know how to do this?
First transform your xml Document Object to String
<%# page import="javax.xml.transform.*" %>
<%
org.w3c.dom.Document list = (org.w3c.dom.Document) session.getAttribute("list");
String xmlAsString = "";
try {
StringWriter sw = new StringWriter();
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.transform(new DOMSource(list), new StreamResult(sw));
xmlAsString = sw.toString();
} catch (Exception ex) {
throw new RuntimeException("Error converting to String", ex);
}
%>
Then you can use pass it to a javascript variable (don't forget the quotes):
<script type="text/javascript">
var list = '<%=list %>';
</script>
Maybe it's also good for you to escape some characters:
var list = '<%=list.replaceAll("'","\\'") %>';
It would be a two step process, first you need to pass the xml from java to javascript as string, like below
var xmlString = "<%=session.getAttribute('list')%>"
and then parse the xml string to XMLDocument. Example using jQuery -
var xml_doc = jQuery.parseXML(xmlString);
For reference :
1. jQuery.parseXML()

How to read the contents of a .txt file, modify it, and display it as an html page on local host in web browser?

I have tried to do this for hours on end with searching the web for answers but none of them produce the results I need.
Currently, I open a .txt file, read the contents and console.log() them in the cmd window. I need to figure out how to output these modified contents onto an html page on the local host.
I create a server at a local host address (127.0.0.1:xxxx) and create a web page where you have hyper text links. I user serverStaticFile() to give it the html file of that page will display they modified version of the .txt file.
I have tried saving the modified version of the .txt file into another .txt file that will be accessed by the html page but only the last line of the original .txt file is saved.
I use lineReader.eachline() because I have to take some parts of the line and put it into another string and then output those strings as the finished product of that line.
lineReader.eachLine( // For every line in the song
'original.txt',
function(line, last) {
var string1 = "";
var string2 = "";
var string3 = "";
var string4 = "";
var stringLine = line;
var skipSpaces = 0;
for (var i=0; i<stringLine.length; i++){ // For every character in the line
if (stringLine[i] == "["){
// If the character is a '[', scan the line until ']' is found.
// Everything in between is for string1
var c = "";
var x = i+1;
var chordString = "";
while (c !== "]") {
chordString += stringLine[x];
x++;
c = stringLine[x];
}
string1 += chordString;
skipSpaces = chordString.length;
i = x;
} else {
// If the character isn't a bracket, add that character to the string2
if (skipSpaces > 0){
// Pad the top line with spaces, unless they should be skipped due to a chord having been added.
skipSpaces--;
} else {
string1 += " ";
}
string2 += stringLine[i];
}
}
console.log(string1);
console.log(string2);
string3 = string1+string2;
string4 += string3;
fs.writeFile("chordpro.txt", string4, function(err) {
if(err) {
console.log(err);
} else {
console.log("");
}
});
if (last) {
return false; // stop reading
}
});
string1 and string2 are the modified contents of the current line being read in the loop.
I save the modified line into one whole string, string3, and try to put all of that into another string that doesn't overwrite the previous modified lines. The problem with this is that it only saves the last line of the original .txt file in the modified.txt file.
I wanted to upload this modified.txt file into the html page which I have not figured out how to do.
Can someone please give me some guidance?
The reason your "chordpro.txt" file only has the last line of the file that's being read from is because for each line in the input file you are writing that line to the output file when you are finished. When you use writeFile() it will overwrite whatever is currently in the file. What you want to do is use appendFile() instead.
fs.appendfile("chordpro.txt", string4, function(err) {
//..
}

Categories

Resources