I don't really know what's going on here. Every time I try to upload a file, all the file contains is:
------WebKitFormBoundaryJ0uWMNv89fcUsC1t--
I have searched for the past 2 days for some sort of explanation, but I am just going in circles. I have no idea why this is happening.
<form id="upload-file" ecntype="multipart/form-data">
<input name="picture" type="file">
<input type="button" value="Upload" id="upload-button" />
</form>
$('#upload-button').click(function(e){
e.preventDefault();
var formData = new FormData($('#upload-file'));
$.ajax({
url: '/image',
type: 'POST',
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){
myXhr.upload.addEventListener('progress',progressHandlingFunction, false);
}
return myXhr;
},
data: formData,
cache: false,
// contentType: false,
processData: false
});
});
def image = Action(parse.temporaryFile) { request =>
request.body.moveTo(new File("/tmp/picture"))
Ok("File uploaded")
}
The problem was occuring in the Javascript, not the Scala. I was not referencing the form elements improperly.
var formData = new FormData($('#upload-file')[0]);
However, I also had problems with parse.temporaryFile
and it was not properly storing the file using the code above. When I inspected the stored files in a text editor, I noticed it still had the ------WebKitFormBoundaryJ0uWMNv89fcUsC1t--
stuff at the beginning of the file, followed by the form information, then followed by the file bytes.
To fix this, I just used the default method for multipartform upload as per the Play Documentation, and it worked perfectly.
def image = Action(parse.multipartFormData) { request =>
request.body.file("picture").map { picture =>
val filename = picture.filename
picture.ref.moveTo(new File(s"/tmp/picture/$filename"))
Ok("ok")
}.getOrElse {
InternalServerError("file upload error")
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With