I am trying to POST an image to imageshack using their API and Play Framework’s WSRequest object.
My code is as follows:
public static void upload( Picture picture ) throws Exception {
//set file parameter - in this case the image
WS.FileParam fp = new WS.FileParam( picture.asFile, "fileupload");
//set other parameters
Map<String,Object> params = new HashMap<String, Object>();
params.put( "optsize", "resample" );
params.put( "rembar", "yes" );
params.put( "public", "no" );
params.put( "a_username", username );
params.put( "a_password", password );
params.put( "key", a_key );
//POST request
Document doc = WS.url( "http://www.imageshack.us/upload_api.php" )
.setHeader( "Content-Type", picture.contentType )
.mimeType( "multipart/form-data" )
.params( params )
.files( fp )
.post()
.getXml();
}
However, I always reveive the following response from imageshack:
Sorry, but we’ve detected that unexpected data is received. Required parameter ‘fileupload’ is missing or your post is not multipart/form-data.
I have tried sending the file as a parameter using a byte array:
params.put( "fileupload", Base64.encode( picture.asBytes ) )
But this also results in the same response from Imageshack.
This is driving me mad. Can anyone point out where I am going wrong or possibly point me in the direction of a better solution? Thanks.
The cause
After a bit of research I found that I had neglected a bit of important information from this question….I am including the Google App Engine module within my app.
According to the Play Framework Google Group the code associated with attaching Files to a WS request when using GAE is actually just commented out. Hence the reason it just doesn’t work. So no error thrown for you and no indication why it doesn’t work…you just have to work it out.
I have accepted @Gary’s answer as it is the correct way to upload an image to imageshack using WS – just not when using GAE.
I don’t think you need to specify the content type or mime type directly.
I used the following code to upload successfully.
I think when you attach a file to a request it automatically decides its going to be multipart/form-data.
This is my entire controller (except for the API Key)
and this is the application.conf file
I didn’t make any other changes. Just browsed to http://localhost:9000/Application.tryUpload and could see the success XML on the play console.