Rectangle 27 0

POST    /upload                                 Application.upload
Application
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>

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 :)

Can this work with multiple uploads?

Yes,there is no "queue" system though you have to implement it yourself it just "drop all the files" in and it uploads, (or select them with the browse button)

you should save it as a snippet, to share with the rest of play developers: playframework.org/community/snippets

That's fantastic! But although links to other sites can be useful adjuncts to answers, the relevant code (even if there's a quite a lot of it) should be contained in the answer itself as well. The content of external sites can change, or move, or disappear entirely. Stack Overflow is meant to be a resource for the OP now, and for others with the question in the future. More: meta.stackexchange.com/questions/8231/

PlayFramework: Ajax + Drag n' Drop + File Upload + File object in cont...

ajax file-upload drag-and-drop playframework
Rectangle 27 0

Use the automatic binding instead of looking in the params:

public class Application extends Controller {

    public static void index() {
        render();
    }

    public static void upload(File[] files)
    {
        for (File file : files)
        {
            Logger.info(file.getName());
        }

        index();
    }
}
#{extends 'main.html' /}
#{set title:'Home' /}

#{form @upload(), enctype:'multipart/form-data'}
    <input type="file" name="files" />
    <input type="file" name="files" />
    <input type="file" name="files" />
    <input type="submit" value="Send it..." />
#{/}

It doesn't work for me :/ (In case, I use Play! v1.2.4 with java 1.6.0_26). I still have a list of as many file as I have uploaded, but with the same name (the first one).

Multiple upload file with PlayFramework - Stack Overflow

file-upload playframework
Rectangle 27 0

public static void overviewsubmit(File fake) {
    List<Upload> files = (List<Upload>) request.args.get("__UPLOADS");
    for(Upload file: files) {
        Logger.info("Size = %d", file.getSize());
    }
}

Without the File fake argument the method will not handle multipart/form-data and you'll get an empty request.args array. If anyone knows the play/standard annotation for it, let me know :)

Multiple upload file with PlayFramework - Stack Overflow

file-upload playframework
Rectangle 27 0

parse.multipartFormData
parse.temporaryFile
maxLength
parse.text(maxLength)
parse.maxLength(maxLength, wrappedBodyParser)
// accepts 10 MB file upload
def save = Action(parse.maxLength(10 * 1024 * 1024, parse.multipartFormData)) { request =>
    request.body match {
        case Left(MaxSizeExceeded(length)) => BadRequest("Your file is too large, we accept just " + length + " bytes!")
        case Right(multipartForm) => {
            /* Handle the POSTed form with files */
            ...
        }
    }
}

Instead of BadRequest it would be more suitable to use EntityTooLarge.

playframework 2.0 - Max file upload size in Play framework 2.0 - Stack...

playframework-2.0
Rectangle 27 0

There is nothing in HTTP that prevents you from uploading 15GB files, or 15TB files for that matter. In theory, there's no maximum size of file Play can handle if chunked transfer encoding is used and the underlying filesystem can handle it. For unchunked requests, the theoretical maximum would be 2 ^ 63 bytes (8192 petabytes), since the underlying webserver - Netty - uses long to handle the Content-Length header.

However, some web browsers use signed/unsigned 32 bit integers to manage content lengths, which put them at a maximum of 2GB or 4GB. Neither Google Chrome, nor Opera, have this limitation, so if your user wants to upload a 15GB file, they should use Google Chrome or Opera.

Play can handle 15GB uploads, though I would strongly advise setting scalaVersion := "2.10.3" in your Build.scala, there was a memory issue with earlier versions of Scala and iteratees.

By default, Play will save multipart/form-data body parts to a temporary files. In Scala, you can change this to stream directly to a database or something similar, by supplying a custom PartHandler. See here for more documentation:

thanks for posting the answer but i tried a lot but unable to upload a file of size more than 2GB from mozilla ,my RAM is 4GB.....help is really nedded

uploading a 15 Gb file and downloading it in playframework for java.is...

playframework-2.0
Rectangle 27 0

You should definitly not storage your files to a database. That is a bad idea. Instead, you should upload your files to some local or distant filesystem and only save the filename/filepath in your database.

Using your database as a file storage engine is a easy and quick to setup solution but it is full of inconvegnients that might really change things later during your project.

it would be nice to see some reasons why it is such a bad practice to store files in DB.

thank you very much, I am now only store file name in the database

There are many circumstances that one might needs to store a file in db. For example, many platforms like Heroku won't let you alter the file system directly and you need to use data base for your file uploads.

playframework - play framework 2 upload file to mySQL - Stack Overflow

playframework playframework-2.0
Rectangle 27 0

Depending on your specific requirements, MongoDB's GridFS will store files for you in a much more efficient and scalable manner than any relational database and filesystem.

There are plenty of MongoDB plugins for Play that support GridFS.

How to upload a file to the database using playframework in Scala - St...

scala playframework playframework-2.0
Rectangle 27 0

First of all you do not need

="multiple"
<input type="file" name="files" multiple id="files" size="30">
enctype="multipart/form-data"
@helper.form(action = routes.MyController.submit(), 'enctype -> "multipart/form-data", 'id -> "myform")

or if you're not

<form action=... enctype="multipart/form-data" id="myform">

In your controller you want to try something like this (for Java, I'm sure its similar in Scala)

//Get all files bound to the form when submitted 
List<FilePart> plate_files = request().body().asMultipartFormData().getFiles();
//Get files from a specific name or id
FilePart myfile = request().body().asMultipartFormData().getFile("files");

Then you can use these the iterate through the FilePart objects

Hopefully its similar in scala

playframework 2.0 - Scala Play 2.0.2 multiple file upload - Stack Over...

scala playframework-2.0
Rectangle 27 0

The closest I can come to answer for Play 1.x is to take a look at the https://github.com/jimmyy/Plupload module. It claims to do chunked upload. There is no clear documentation for this, and it is not in the official repository, but it may offer a good start for you.

Failing that, Play 2.x has support for chunked uploads (if you do a search it will be one of the first responses).

playframework streaming file upload "through" play not using their Blo...

playframework
Rectangle 27 0

So... you want to upload video using Rest-full interface. hmmm..... you seem to have not understood the concept of rest yet. I get the feeling that you currently think JSON as an integral part of Rest-full interfaces. And are actually trying to create a Rest-full interface which talks using JSON.

A Restful interface can be provided for uploading smaller files such as pictures etc ( by byte64 encoding them ). Since videos can be considerably large, this method should not be used in this case.

But still, I can give you a pointer in one of the right directions.

One of the ways people do is in steps.

There are other ways to achieve this too, but I think this should provide you some help.

Playframework 2.3.x: Upload videos and large files using rest Web-Serv...

web-services scala rest playframework-2.3
Rectangle 27 0

route for a given Request[T] requires an implicit parameter of type Writeable[T] that knows how to serialize the request body, because it will actually call the controller action just like an actual web request would, by pushing bytes onto it.

Writeable[MultipartFormData]
play.api.test.Writeables

This means you basically have two options:

  • write your own Writeable that serializes a MultipartFormData into bytes
  • Skip the routing part and call the action directly instead, like in the accepted answer in Play Framework Testing using MultipartFormData in a FakeRequest. This way of testing actions takes a shortcut and does not actually serialize and deserialize the request.

IMHO the first option is way too much pain for the gain, but if you go down that road, maybe contribute it to play when you succeed.

I'm not sure where you think I copy pasted these options from. I actually spent a good fifteen minutes out of my free time reading play test helper source code to find an answer for you. But you are very welcome, good luck!

scala - PlayFramework Testing: Uploading File in Fake Request Errors -...

scala testing playframework
Rectangle 27 0

package customcontrollers

import controllers.Assets
import play.api.mvc.Action
import play.api.mvc.AnyContent
import play.api.mvc.Results.Ok
import play.api.Play.current
import play.api._

object UploadedImageAssets {
  def at(file: String): Action[AnyContent] = Action {
    Ok.sendFile(Play.getFile("public/uploaded-images/"+file))
  } 
}

playframework - Play! Framework: File not served after upload until pl...

playframework playframework-2.0
Rectangle 27 0

Although sending files as an action's Result is possible (what you proved) I'd suggest to store public uploads outside of the application and serving it with common HTTP server.

  • if you will need to add/replace files fast, you can do it with common FTP client
  • you don't need to redeploy your app if you're adding files with 3rd part client
  • HTTP server serves static files just faster, it manages cache headers out of the box (cause it's its job) etc. Server doesn't need to rewrite file to the result.
  • using subdomain for this, you can create a'la CDN solution

playframework - Play! Framework: File not served after upload until pl...

playframework playframework-2.0
Rectangle 27 0

I don't like this answer, but there is no way to achieve this easily.

The best solution is to store your file in a database, or to upload it to another service like S3.

Thanks. The easiest solution would be to disable caching on the Assets object. Now I wrote a custom Assets singleton that replaces the built-in Assets class...

playframework - Play! Framework: File not served after upload until pl...

playframework playframework-2.0
Rectangle 27 0

You can solve this problem in two stage:

  • You need to split huge file into smaller chunks and then send them to the server. To achieve this you may use some javascript libraries, for example Resumable.js
  • In your play2 controller you need to assemble these chunks using Iteratee API and then your can do what ever you want with your file.

Let's use resumable.js as example for the client side, I will not dive into the details, you can find a documentation and the examples here

Our view will be minimalist(only link to select a file or files) :

@()
@main("File upload"){
    <a href="#" id="browseButton">Select files</a>
}
$(function(){
var r = new Resumable({
    target:'/test/upload'
});

r.assignBrowse(document.getElementById('browseButton'));

r.on('fileSuccess', function(file){
    console.debug(file);
});
r.on('fileProgress', function(file){
    console.debug(file);
});
// more events, look API docs
@(title: String)(content: Html)

<!DOCTYPE html>

<html>
    <head>
        <title>@title</title>
        <link rel="stylesheet" media="screen" href="@routes.Assets.at("stylesheets/main.css")">
        <link rel="stylesheet" media="screen" href="@routes.Assets.at("stylesheets/style.css")">
        <link rel="shortcut icon" type="image/png" href="@routes.Assets.at("images/favicon.png")">
        <script src="@routes.Assets.at("javascripts/jquery-1.9.0.min.js")" type="text/javascript"></script>
        @*We include resumable.js library*@
        <script src="@routes.Assets.at("javascripts/resumable.js")" type="text/javascript"></script>
        @*Our javascript for file upload*@
        <script src="@routes.Assets.at("javascripts/upload.js")" type="text/javascript"></script>
    </head>
    <body>
        @content
    </body>
</html>

And our server side, in play controller :

First we need to create a function that will treat our file part by consuming our chanks and producing the result - Array[Byte] in our example.

// hadle file part as Array[Byte]
  def handleFilePartAsByteArray: PartHandler[FilePart[Array[Byte]]] =
    handleFilePart {
      case FileInfo(partName, filename, contentType) =>
        // simply write the data to the a ByteArrayOutputStream
        Iteratee.fold[Array[Byte], ByteArrayOutputStream](
          new ByteArrayOutputStream()) { (os, data) =>
          os.write(data)
          os
        }.mapDone { os =>
          os.close()
          os.toByteArray
        }

then we can define a custom body parser:

// custom body parser to handle file part as Array[Byte]
  def multipartFormDataAsBytes:BodyParser[MultipartFormData[Array[Byte]]] =
    multipartFormData(handleFilePartAsByteArray)

and in the end our controller may looks like:

def handleFileUpload = Action(multipartFormDataAsBytes){ request =>
 // retrieve file name from data part   
 val fileName  = request.body.asFormUrlEncoded.get("resumableFilename").get.headOption
 // retrieve arrays of byte from file part and write them to file
    request.body.files foreach{
      case FilePart(key,filename,content,bytes)=>
        import scalax.io._
        val output:Output = Resource.fromFile(fileName.getOrElse("default"))
        output.write(bytes)
    }
    Ok("")
  }

List of imports for the controller :

import play.api.mvc._
import play.api.mvc.BodyParsers.parse.Multipart._
import play.api.libs.iteratee.Iteratee
import java.io.ByteArrayOutputStream
import play.api.mvc.BodyParsers.parse._
import play.api.mvc.BodyParsers.parse.Multipart.FileInfo
import play.api.mvc.MultipartFormData.FilePart

playframework 2.0 - how to upload a huge file in play framework? - Sta...

playframework-2.0
Rectangle 27 0

You may have to overload the function.

def IsAuthenticated[A](p: BodyParser[A])(f: => String => Request[A] => Result): Action[A] ={
    ...
   }

    def IsAuthenticated[AnyContent](f: => String => Request[AnyContent] => Result): Action[AnyContent] = 
       IsAuthenticated(BodyParsers.parse.anyContent)(f)

playframework - How do I secure file upload in Play! Framework (Scala)...

scala playframework
Rectangle 27 0

It looks like solution is very simple. I should keep files in my own cache till I use them in Akka worker. After processing with Akka I could delete it myself. The reason of such behaviour is not to waste file descriptors. Files fetched from request will be deleted before Akka starts. Anyway this is just a guess. I'll try it now.

P.S. Yes. There is a problem. Solution is to keep those files as temporary and delete only after processing.

File upload questions are often asked, could you please update the question and add proper code of the solution that is working for you?

playframework 2.0 - Play Framework 2. Multiple file uploading and proc...

playframework-2.0
Rectangle 27 0

yes, i.e. using curl and then handling it in Play as common form data, other obvious way is just using common form...

playframework - Is there a way to upload file directly with rest api? ...

playframework playframework-2.1 playframework-2.2
Rectangle 27 0

Does that compile? Youre passing a java.io.File object to doFileUpload, whose first parameter is an InputStream.

This example is too complicated, i'm writing code as I'm looking at the answers, thus editing my post with different versions of the application. I'm going to edit my first post with a very simple file upload application. Thanks for your answer. Hope to hear from you soon!

playframework - Basic file uploading fails - Stack Overflow

file-upload playframework
Rectangle 27 0

If you have multiple inputs with the same name, the controller will receive those files with the given name as an array, e.g.

public static void upload(File[] files) {
    ...
}
#{form @upload(), enctype:'multipart/form-data'}
<input type="file" name="files">
<input type="file" name="files">
<input type="file" name="files">
<input type="submit" value="Upload" />
#{/form}

You can always add a bit of javascript to allow the user to add additional inputs on the client side

playframework - Play framework multiple file upload - Stack Overflow

playframework