【问题标题】:Play framework upload file not working播放框架上传文件不起作用
【发布时间】:2012-11-14 19:47:41
【问题描述】:

我想上传一个 CSV 文件并从那里获取详细信息以填充 MySQL 数据库。我正在使用播放!框架 2 与 Java,但我很难实现这个解决方案。

这是我的 Java 代码

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

这是我的 Upload.Scala.html 代码

   @(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>

      }
   }

最后是我的路线文件

POST     /uploadfile                controllers.Application.uploadfile()

一旦我点击上传,就会发生执行异常,说request().body().asRaw().asFile() 实际上是null

[NullPointerException: null]

任何想法我做错了什么?

================================================ ===================================== 好的,所以我当前的代码如下 在 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());    
    }
}

在 ImportCSV.java(扩展模型)上

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

    }

一旦我通过缓冲阅读器,数据为空。一开始我尝试将文件(File fl)发送到参数,但我也得到了空错误。我尝试了在某些情况下显示的 @Util 注释,但编译器抱怨无法识别它! 我愿意接受建议!

【问题讨论】:

    标签: playframework playframework-2.0


    【解决方案1】:

    这里有关于如何执行此操作的说明: http://www.playframework.org/documentation/2.0/JavaFileUpload

    request().body().asRaw().asFile(); 仅在您使用 ajax 上传文件时有效,如果您使用普通的POST 请求,您应该尝试使用文档中提出的解决方案

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

    还要注意你必须使用正确的表单格式,这里:

    @form(action = routes.Application.upload, 'enctype -&gt; "multipart/form-data")

    【讨论】:

    • 感谢您的回复!我确实更改了代码,但是一旦我将文件传递给另一个函数以解析该函数​​,就会调用一个异常,因为文件为空!我什至试图将文件放入缓冲阅读器并发送它,但仍然......纳达!在函数之前使用 @Util 会在编译期间因找不到 u 而导致错误!!!!!
    • 如果你的意思是文件从表单转换到结果函数,它似乎可以工作。但否则文件不会以任何方式发送到辅助功能。有什么想法可以解决这个问题吗?
    • 我不太确定你要做什么,你能添加一些示例代码吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-17
    • 1970-01-01
    相关资源
    最近更新 更多