Does anyone know of a way to upload a file via Ajax and using drag n' drop from the desktop that supports PlayFramework's ability to convert file uploads to a File object?
I've tried several different methods, and nothing works correctly.
Here's my successful attempt:
Edit routes file and add
POST /upload Application.upload
Our controller is Application
, I'll be using it to keep it simple.
Edit your Application controller class
public static void upload(String qqfile) {
if (request.isNew) {
FileOutputStream moveTo = null;
Logger.info("Name of the file %s", qqfile);
// Another way I used to grab the name of the file
String filename = request.headers.get("x-file-name").value();
Logger.info("Absolute on where to send %s", Play.getFile("").getAbsolutePath() + File.separator + "uploads" + File.separator);
try {
InputStream data = request.body;
moveTo = new FileOutputStream(new File(Play.getFile("").getAbsolutePath()) + File.separator + "uploads" + File.separator + filename);
IOUtils.copy(data, moveTo);
} catch (Exception ex) {
// catch file exception
// catch IO Exception later on
renderJSON("{success: false}");
}
}
renderJSON("{success: true}");
}
Edit your Application.html in app/views/Application folder/package
#{extends 'main.html' /}
#{set title:'Multiple Uploads' /}
<div id="file-uploader">
<noscript>
<p>Please enable JavaScript to use file uploader.</p>
<!-- or put a simple form for upload here -->
</noscript>
<script>
function createUploader(){
var uploader = new qq.FileUploader({
element: document.getElementById('file-uploader'),
action: '/upload',
debug: true
});
}
// in your app create uploader as soon as the DOM is ready
// don't wait for the window to load
window.onload = createUploader;
</script>
</div>
Edit your main layout: main.html, located in the app/views folder/package and add this line after jQuery
<script src="@{'/public/javascripts/client/fileuploader.js'}" type="text/javascript"></script>
Final notes Remember to download the script from AJAX Upload Valums, enjoy!
You can also grab the source here.
I tested it in different browsers it works for me at least. Credits to Riyad in Play! mailing list who hinted me about the request.body
P.S: I'm using the one I posted as a comment before
Edit The answer with code has been added as directed by T.J. Crowder, I agree :)
The simple upload part (not drag&drop just click on "upload a file") is not working with Ie7 & 8 (don't try others ie)
See getting Java Bad File Descriptor Close Bug while reading multipart/form-data http body
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