Multipart/form-data submit through javascript in Play Framework


Normally when we submit any multi-part form in Play Framework that time in the controller have to mention redirection action which  refresh the whole page and it gives an extra load on the network.

It is possible to submit that form with the help of Ajax. It makes easy to submit your form and help to refresh only that particular section where you want to reflect the changes.

1.  We create a multi-part form for uploading the file and some other information.

<form id="profileForm" enctype="multipart/form-data">
<input type="file" name="fileUpload">
<input type="submit" value="Upload" id="ajaxCallUpload">
</form>

2. We develop an Ajax call for submitting form we use  FormData. The FormData object lets you compile a set of key/value pairs to send using XMLHttpRequest. It is primarily intended for use in sending form data, but can be used independently from forms in order to transmit keyed data.

When we call that Ajax call than in the FormData we passed the form_ID so that it makes its object.

We define some important things like –

1. type of call,

2. url on which we have to send data,

3. headers,

4. dataType it can be json,

5. processData it could be false or true,

6. contentType it can be false or application/json ,

7. data we pass that data which we find from the form.

We also mention its success where mention what we have to do when call will be success and error where we mention what we have to do when call will be failed.

$("#ajaxCallUpload").click(function (e) {
var formData = new FormData($("#profileForm")[0]);
e.preventDefault();
$.ajax({
type: "POST"
url: '/upload',
headers: { 'IsAjax': 'true' },
dataType: "json",
processData: false,
contentType: false,
data: formData,
success: function (result) {
onSuccessUpload(data);
},
error: function (error) {
onErrorUpload(error)
}
});
});
var onSuccessUpload = function (result) {
if(result == "File uploaded"){
alert("file uploaded successfully.")
}else{
alert("file not uploaded. Try again !!!")
}
}
var onErrorUpdateProfile = function (error) {
alert("Oops !! Something went wrong.")
}

3. Define Post request in routes for call the action in controller.

POST  /upload  @controllers.UserController.uploadFile

4. Define an action in the UserController.

val uploadService: UploadService

def uploadFile = ScuredAction.async { implicit request =>
val temporaryFile: Option[MultipartFormData[TemporaryFile]] = request.body.asMultipartFormData
val result = uploadService.uploadData(temporaryFile)
Ok(result)
}

5.  Create a service which take your data and saved it.

def uploadData(requestedData: Option[MultipartFormData[TemporaryFile]]): String = {
log.error("Called uploadFile function" + request)
requestedData foreach { fileData =>
fileData.file("file").map {image =>
import java.io.File
val filename = image.filename
val contentType = picture.contentType
log.error("File name : $filename, content type : $contentType")
picture.ref.moveTo(new File("tmp/$filename"))
"File uploaded"
}.getOrElse {
"Missing file"
}
This entry was posted in AJAX, JavaScript, MultipartFormData, Play Framework, Scala and tagged , , , . Bookmark the permalink.

2 Responses to Multipart/form-data submit through javascript in Play Framework

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s