Question

I am trying to upload image to mySQL using play framework2.

In play framework 1.24, I use "play.db.jpa.Blob" and "multipart/form-data" to upload an image to the mySQL.

But in play framework2 there is no Blob... How can I upload the image using "multipart/form-data" to mySQL?

Was it helpful?

Solution

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.

EDIT : Since my answer as downvoted, I'll try to give a little more explanation :

  1. First of all, when working with Blob types in Play framework, it will create a BLOB field in your database. But, not all database have the same implementation behind the blob type. In some RDMS, the Blob type will have limited storage and in other (such as MySQL) the maximum size of your blob field will be determined by configuration.

  2. Secondly, when you are retrieving your files from the database and sending them to the user, your memory usage is going to explode. Very simply because, Play loads the blob field into memory before sending it to the user.

  3. Plus, if you have lots of files stored in your database, it will be overloaded very quickly. (requests). You next move will be moving the database on a new machine. But if you have much data stored, your next bottleneck might not be the database but the bandwith between your application and the database server.

  4. Using a database for file storage is always going to be slower and consuming more memory than direct filesystem reading because of the overhead created by the 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.

OTHER TIPS

Another way, you can store reference to photo in database.

In view:

<form action="@routes.Application.index" method="POST" enctype="multipart/form-data">
           Photo<input type="file" name="photo"> <br>
             <input type="submit" value="Submit">    
</form>

In controller:

MultipartFormData body = request().body().asMultipartFormData();
            FilePart photo = body.getFile("photo");
            if (photo != null) {
                String fileName = photo.getFilename();
                File file = photo.getFile();
                File newFile = new File(play.Play.application().path().toString() + "//public//uploads//"+ "_" + fileName);
                file.renameTo(newFile); //here you are moving photo to new directory          
                System.out.println(newFile.getPath()); //this path you can store in database
            }
}

This is what the Blob object handles transparent. It stores the file in the filesystem and store a reference in the db.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top