How to upload file/image

18 views
Skip to first unread message

Kwizzy FR

unread,
Nov 28, 2016, 6:50:38 AM11/28/16
to Play Framework

I want to upload file/image on my website. Actually i can upload my file but sometimes i've error on my page and i think it's not the good way to do this.

My code :


private String uploadImage()
{
    String result = f.validate("avatar");
    if(result.isEmpty())
        return "none";
    Http.MultipartFormData.FilePart<File> file = body.getFile("avatar");

    if(file == null)
        return "File is empty or not exist.";

    String filename = file.getFilename();

    /* Debug file file*/
    Logger.debug("nameFile " + file.getFilename());
    Logger.debug("contentFile " + file.getContentType());
    /* End debug*/

    File f = file.getFile();

    /* Debug file f*/
    String name = f.getName();
    long totalSpace = f.getTotalSpace();
    Logger.debug("nameF " + name);
    Logger.debug("sizeF " + totalSpace);
    /* End debug*/

    try {
        /* File user is not f file variable*/
        File fileUser = getFileUser(filename);
        Try.of(fileUser::delete);

        /* Use of org.apache.commons.io*/
        FileUtils.moveFile(f, getFileUser(filename));
    } catch (IOException e) {
        e.printStackTrace();
    }
    return "";
}

private File getFileUser(String fileName)
{
    return new File("public/upload/avatars",
                     user.getId().toString() + "." + FilenameUtils.getExtension(fileName));
}

private boolean fileIsPicture(File f)
{
    String mimetype = new MimetypesFileTypeMap().getContentType(f);
    String type = mimetype.split("/")[0];
    return (type.equals("image"));
}


Error :


java.io.FileNotFoundException: Source 'C:\Users\Alexis\AppData\Local\Temp\playtemp1188878075698565675\multipartBody8627595002998720963asTemporaryFile' does not exist


But i've a debug with some informations (Why 2 times debug?):


[info] play.api.Play - Application started (Dev)
[info] application - avatar  null
[debug] application - nameFile KwizzyPicture.jpg
[debug] application - contentFile image/jpeg
[debug] application - nameF multipartBody1959853090277810547asTemporaryFile
[debug] application - sizeF 763679993856
[info] application - avatar  null
[debug] application - nameFile KwizzyPicture.jpg
[debug] application - contentFile image/jpeg
[debug] application - nameF multipartBody1959853090277810547asTemporaryFile
[debug] application - sizeF 0


Full code here


Thank you for your help ! I'm french so sorry for mistakes.

Hannah J Swystun

unread,
Nov 29, 2016, 8:46:13 AM11/29/16
to Play Framework
Hi,

Look at this example : https://github.com/DirtyDan88/play-framework-blob
You have the Image as an object.

If you have troubles with the sample above, i can help you directly.

Hope this help.
Reply all
Reply to author
Forward
0 new messages