2012-04-12 126 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 
相關問題