Playframework Multiple File Upload - java

I am using JavaFileUpload and want to upload multiple pdf files.
HTML part:
#helper.form(action = routes.Application.uploadPost, 'enctype -> "multipart/form-data") {
<input type="file" id="inputFile" name="pdf" accept="application/pdf" multiple autofocus >
<p>
<input type="submit">
</p>
}
I must change body.getFile("pdf") asbody.getFiles() to be able to get every pdf document that I want to upload successfully.
I can see every document if I use getFiles() and if I use getFile("pdf") it just selects first document.
I tried to upload five pdf documents and here is the difference between getFiles() and getFile("pdf")
output of getFiles(): [play.mvc.Http$MultipartFormData$FilePart#3ac08835, play.mvc.Http$MultipartFormData$FilePart#362e6db5, play.mvc.Http$MultipartFormData$FilePart#2224a1dd, play.mvc.Http$MultipartFormData$FilePart#12fec5ae, play.mvc.Http$MultipartFormData$FilePart#14642c40]
output of getFile("pdf"): play.mvc.Http$MultipartFormData$FilePart#3ac08835
in the Java part, if I change getFile("pdf") as getFiles(), it tells me to add cast. So it offers me two options. One is to add FilePart cast, second is to change type of pdf to List<FilePart>
If I add FilePart cast for getFiles() like this FilePart pdf = (FilePart) body.getFiles(); PlayFramework shows me an exception: [ClassCastException: scala.collection.convert.Wrappers$SeqWrapper cannot be cast to play.mvc.Http$MultipartFormData$FilePart]
If I change type of pdf to List<FilePart>, it then offers me to add a cast to pdf.getFilename() like this: ((FilePart) pdf).getFilename(), also it offers me to add two casts to File file = pdf.getFiles() like this: File file = (File) ((MultipartFormData) pdf).getFiles(). If I run the code I also get the same exception.
Is there any way to upload multiple pdf documents in this case?
Half code: ( I can add full code if needed. The rest of code is parsing by using PDFBox and indexing into Solr and HBase
import play.mvc.Http.MultipartFormData;
import play.mvc.Http.MultipartFormData.FilePart;
MultipartFormData body = request().body().asMultipartFormData();
for(int i=0; i<body.getFiles().size(); i++) {
body = request().body().asMultipartFormData();
FilePart pdf = body.getFile("pdf"); //getFiles();
String fileName = pdf.getFilename();
File file = pdf.getFile(); //getFiles();
...
Play framework version: 2.4

First, the difference between getFiles() and getFile("pdf") is former gets list of files while latter get only one file.
Try the following code.
List<FilePart> fileParts = request().body().asMultipartFormData().getFiles();
for(FilePart filePart : fileParts) {
filePart.getFile();
}

Related

JAVA - Write into html files

I am looking to write inside an html file using java.
I have my index.html page ready and I would like to use this template and add a name list (with hyperlinks to go to their pages) at a certain place in this page.
Is it possible to use beacons or tags to tell java to write to this exact location in the html file?
I will use this type of java code to write, the array will be a names array btw, but it's in this mind:
String[] labelEquipment = { "thing1", "thing2", "thing3", "thing4",
"thing5", "thing6", "thing7", "thing8", "thing9",
"thing10" };
PrintWriter f0 = new PrintWriter(new FileWriter("filename.txt"));
for (String string : labelEquipment) {
f0.println(string);
}
f0.close();
You can create a html file like this :
<body>
{{my_placeholder}}
</body>
Using java, you can read this file as string and then use .replace('{{my_placeholder}}',your_content) to replace the place holder with individual label equipments. The variable your_content will have to be group of html tags that will be placed in your html in place of my_placeholder

How to write data to pdf file which contains html tags using itext lib in Java

I have String which contains some html tags and it is coming from database, i want to write that in PDF file with same styling present in the String in the form of HTML tag. I tried to use XMLWorkerHelper like this
String html = What is the equation of the line passing through the
point (2,-3) and making an angle of -45<sup>2</sup> with the positive
X-axis?
XMLWorkerHelper.getInstance().parseXHtml(writer, document, new
StringReader(html));
but it only reads the data which is inside the html tag(in this case only 2) other string it simply ignores. But i want the entire String with HTML formating.
With HTMLWorker it works perfectly but that is deprecated so please let me know how to achieve this.
I am using iText 5 lib

How to customize the request from HTML to Servlet

I am building a server using Java's servlet and HTML forms.
I already managed to upload files: the user reach an HTML page, chose the file he/she wants to upload in his/her tree folder. The file is sent to a servlet I've written and downloaded on the server (actually I'm only running it on localhost for the moment, so the server is my 'My Documents' folder).
The next step I would like to make is this one:
The user (once logged, but I will manage to do that) reaches an HTML page, select a file that is hosted by the server and download it.
To make it, I will have to send to the 'Download Servlet' the name of the file. So here are my questions:
How to list the files that are in 'My Documents' on the HTML page.
How to send the name of the selected file to the servlet.
How to catch the 'request' and make a String of the name out of it.
To precise these two lasts points, please have a look at this:
List<FileItem> items = null;
items = upload.parseRequest(request);
FileItem item = items.get(0);
String fileName = item.getName();
The block above catches the name of the folder that is in the request. What I actually want to do is to do the same thing if what is in the request is a String (=catch the String contained in the request).
The File API will give you what you need for selecting the files in your directory.
List<File> files = Arrays.asList(new File("/your/directory").listFiles());
List<String> fileNames = new LinkedList<>();
for (File file : files) {
fileNames.add(somePrefix + file.getName());
}
request.setAttribute("fileNames", fileNames);
I do the above because you might not want to give the real path to your files, for security reasons. Once you have the list of file names in your request attributes, you can iterate over them in a jsp.
<form ...>
Select a file:<br />
<c:forEach items="${fileNames}" var="fileName">
<input type="radio" name="fileName" value="${fileName}">
</c:forEach>
<input type="submit" name="submit" value="submit">Submit
</form>
Now the files are each attached to an input element, which will translate to a request parameter. When the form is submitted, you can access the select file name by doing
String fileName = request.getParameter("fileName");
You can then append that file name to some directory structure and go and find it on the file system.

Create image form byte array , add it in a PDF and email by backend job

My question is that how can we create image form byte array without response.
currently I am using .
response.setHeader('Content-length', image.imageSize)
response.contentType = image.imageFormat // or the appropriate image content type
response.outputStream << image.imageData
response.outputStream.flush()
but it gave error because we done have an request object as I am running this by back end job
Don't know how you are creating your pdf files at the moment, but one way would be using the Grails Rendering Plugin for pdf generation. With this, you could use any view/template to generate a pdf file.
To send these pdfs from backend you'll need:
A View:
<html>
<head>...</head>
<body>
<h1>Your PDF Content</h2>
<g:each in="${images}" var="image">
<img src="${createLink(action:'displayImage', id:image.id)}" alt="${image.name}"/>
</g:each>
</body>
</html>
An action in your controller:
def displayImage = {
def image = Image.get(params.id)
response.setHeader("Content-disposition", "attachment; filename=${image.name}")
response.contentType = image?.mimeType
response.contentLength = image?.data.length
response.outputStream.write(attachment?.data)
}
A grails job that sends the multipart mail (using the mail plugin ) with the rendered pdf:
def execute() {
def pdfBytes = pdfRenderingService.render(template: '/path/to/your/template', model: [images: yourImages]).toByteArray()
sendMail {
multipart true
to "yourmail"
subject "yoursubject"
body (view: "/path/to/your/mailview", model: yourModel) attachBytes "yourTitle.pdf", CH.config.grails.mime.types['pdf'], pdfBytes
}
}
The code is not complete, it just demonstrate the basics.
Hope that helps!

How to get all file paths while using html "file" input with multiple attribute

I am developing a web page in which I have to upload multiple files on
a single browse.
I am using html <input id="filelist" type="file" multiple=multiple>
This enables the multiple file selection and also retrieves the
full file path of all the selected file, which shows in file
upload text area.
<script language="JavaScript">
<!--
function showname(){
var filepath = document.form1.filelist.value ;
alert(filepath); //this shows only first filename among selected file
}
-->
</script>
But the problem is when I get the value of input, it returns only the first file
name among selected files.
Now how can I get the file paths which is shown in file upload text area.
Thanks!
This is browser specific. So you might be running this in a browser that doesn't support this. For example Firefox does. Here's an example of how to use this feature:
http://hacks.mozilla.org/2009/12/multiple-file-input-in-firefox-3-6/
I would consider using http://www.uploadify.com/about/ or http://www.fyneworks.com/jquery/multiple-file-upload/. They should help you out, and also add some cool features to your file upload form.
File paths are deliberately hidden from the page for security purposes. To look at the local filesystem you need to use Java, Active-x (meh), or Flash.

Categories