Reputation: 21
I wanted to upload a CSV file and from there get the details in order to fill up a MySQL database. I am using Play! framework 2 with Java but i am having difficulties to implement this solution.
This is my Java code
public static Result uploadfile() {
File fl = request().body().asRaw().asFile();
if (fl != null) {
return ok("File uploaded");
} else {
flash("error", "Missing file");
return redirect(routes.Application.index());
}
This is my Upload.Scala.html code
@(uploadForm: Form[Application.upl])
@import helper._
@main("Upload file") {
@form(action = routes.Application.uploadfile) {
<input type="file" name="flname">
<p>
<input type="submit" value="upload">
</p>
}
}
And finally my routes file
POST /uploadfile controllers.Application.uploadfile()
Once I hit upload an execution exception occurs saying that the request().body().asRaw().asFile()
is actually null
!
[NullPointerException: null]
Any ideas what I am doing wrong?
=================================================================================== Ok so my current code is as follows On application.java
public static Result uploadfile() {
play.mvc.Http.MultipartFormData body = request().body().asMultipartFormData();
FilePart flpart = body.getFile("fl") ;
if (flpart != null) {
File file = flpart.getFile();
ImportCSV impCSV = new ImportCSV();
try{
if (file.exists())
{
BufferedReader br = new BufferedReader( new FileReader(file));
System.out.println(file.getName() + " - " + file.getAbsolutePath());
impCSV.importCSV(br);
}
else
{
System.out.println("File not found!");
return redirect(routes.Application.upload());
}
}
catch(Exception e)
{
System.err.println("Buffering file " + file.getName() +": " + e.getMessage());
}
return ok("File uploaded");
} else {
flash("error", "Missing file");
return redirect(routes.Application.index());
}
}
And on the ImportCSV.java (which extends model)
public static void importCSV( BufferedReader br)
{
parseFile(br);
if(vals!=null)
{
Student student = new Student();
List<Student> newStudents;
newStudents = GetStudentDetails(vals);
try{
student.insertStudentList(newStudents);
}
catch(Exception e)
{
System.err.println("student inserting Error: " + e.getMessage());
}
}
}
static void parseFile( BufferedReader br) {
try {
String line = "";
StringTokenizer token = null;
int lineNum = 0, tokenNum = 0;
List<values> CSVvalues = new LinkedList<values>();
values LnValues = new values();
while((line = br.readLine()) != null) {
lineNum++;
// break comma separated file line by line
token = new StringTokenizer(line, ",");
LnValues = new values();
while(token.hasMoreTokens()) {
tokenNum++;
switch(tokenNum)
{
//Student ID
case 0:
{
LnValues.setStudID(Long.getLong(token.nextToken()));
}
//Student Name
case 1:
{
LnValues.setStudName(token.nextToken());
}
//Student DoB
case 2:
{
LnValues.setStudDoB(Date.valueOf(token.nextToken()));
}
//Class
case 3:
{
LnValues.setCl(token.nextToken());
}
//Year
case 4:
{
LnValues.setYear(Integer.parseInt(token.nextToken()));
}
//Quarter
case 5:
{
LnValues.setQuarter(token.nextToken());
}
//Maths Grade
case 6:
{
LnValues.setGradeM( Float.parseFloat(token.nextToken()));
}
//Computer Science Grade
case 7:
{
LnValues.setGradeCS(Float.parseFloat(token.nextToken()));
}
//Literature grade
case 8:
{
LnValues.setGradeL( Float.parseFloat(token.nextToken()));
}
}
}
CSVvalues.add(LnValues);
tokenNum = 0;
}
vals = CSVvalues;
} catch(Exception e) {
System.err.println("Parsing file Error: " + e.getMessage());
}
Once i pass the Buffered reader the data are null. At the beginning i tried to send the file (File fl) to the parameters but i also got null error. I tried @Util annotation shown in some cases but the compiler complains for not recognizing it! I am open to suggestions!
Upvotes: 2
Views: 4245
Reputation: 515
There are instructions on how to do this here: http://www.playframework.org/documentation/2.0/JavaFileUpload
request().body().asRaw().asFile();
only works if you are using ajax to upload the file, if instead you are using the normal POST
request, you should try the solution proposed in the documentation by using
public static Result upload() {
MultipartFormData body = request().body().asMultipartFormData();
FilePart picture = body.getFile("picture");
if (picture != null) {
String fileName = picture.getFilename();
String contentType = picture.getContentType();
File file = picture.getFile();
return ok("File uploaded");
} else {
flash("error", "Missing file");
return redirect(routes.Application.index());
}
}
Also notice that you have to use the correct form format, here:
@form(action = routes.Application.upload, 'enctype -> "multipart/form-data")
Upvotes: 3