2012-04-12 64 views
0

我们使用的是Play Framework 2.0。为REST请求提供服务。我们希望能够将文件传递给POST请求,并能够在我们的Contoller中处理它。在Play框架中将文件传递到POST请求

我结束了以下内容:

GET /customer/:id/photos controllers.PhotosController.addPhoto(id: Integer, page: String) 

我试图让该文件在控制器代码,但没有运气的内容。

我会发送POST请求以下列方式:

curl.exe -X GET localhost:9000/customer/23/photos?page=Sun.jpg 

任何想法如何处理这种情况?

+0

现在我注意到我使用了不正确的url。所以问题是如何模拟用curl发送文件内容? – Jakub 2012-04-12 12:57:32

+0

* curl.exe -X GET *命令不会发送POST ...请查看http://superuser.com/questions/149329/what-is-the-curl-command-line-syntax-to -do-a-post-request和http://paulstimesink.com/2005/06/29/http-post-with-curl/ – 2012-04-12 15:18:22

+0

此外,您的控制器正在接收* String *而不是* File * – 2012-04-12 15:25:27

回答

0
//add this line in you controller 

static play.data.Form<Model> modelForm = form(Model.class); 

public static Result addPostSave(){ 
    try{ 
     MultipartFormData body = request().body().asMultipartFormData(); 
     FilePart picture = body.getFile("picture"); 
     File pic = picture.getFile(); 
if(filledForm.hasErrors()){ 
       return ok(addPost.render(postForm)); 
      }else{    
       Post post = new Post(); 
       post.picture = pic; 
       post.save(); 
       return ok(index.render("The image is created")); 
      } 
    }catch(IOException e){ 
     return ok(e.to_string) 
    }  
} 
0

我相信你的控制器看起来应该像:

public static void addPhoto(Integer id, File page){} 

路线:

POST /customer/:id/photos controllers.PhotosController.addPhoto(id: Integer, page: File) 

而且您的测试要求应该是这个样子:

curl.exe -F [email protected] localhost:9000/customer/23/photos 

(在比赛中测试1.2.3)

0

在玩2.0,你那样做:

控制器(只是一个例子):

public static Result addPhoto(Integer id){ 
    MultipartFormData body = request().body().asMultipartFormData(); 
    FilePart file = body.getFile("page"); 
    System.out.println(file.getFilename()); 
    System.out.println(file.getFile().getAbsoluteFile()); 
    return ok(); 
} 

路线

POST /addphoto/:id controllers.PhotosController.addPhoto(id: java.lang.Integer) 

curl命令

curl --header "enctype -> multipart/form-data" -F [email protected]/path/to/file localhost:9000/addphoto/23 
相关问题