Alican Balik
Alican Balik

Reputation: 1294

Playframework Multiple File Upload

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.

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

Upvotes: 1

Views: 983

Answers (1)

Santhoshle
Santhoshle

Reputation: 643

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

Upvotes: 2

Related Questions