Andreas Fritsch
Andreas Fritsch

Reputation: 242

change upload path play framework

I am trying to change the saving path for images. If I debug I see the following path:

 /tmp/playtemp4579361689183556686 

I thought I will change the path with the directory with the command:

file.renameTo(new File(path))

Do some one know how I can change the path? Where I did the mistake?

The whole code is below.

public Result doUpload() {

    Http.MultipartFormData<File> body = request().body().asMultipartFormData();
    Http.MultipartFormData.FilePart<File> picture = body.getFile("picture");

    Path uploadPath = environment.rootPath().toPath();

    final String uploadFolder = "/public/uploads/";

    if (picture != null) {
        String fileName = picture.getFilename();
        String contentType = picture.getContentType();
        File file = picture.getFile();
        String path = uploadPath + uploadFolder + fileName;

        Logger.info("path: {}", uploadPath);
        Logger.info("whole path: {}", path);

        file.renameTo(new File(path));

        return ok("File uploaded");
    } else {
        flash("error", "Missing file");
        return badRequest();
    }
}

Upvotes: 0

Views: 620

Answers (2)

Rotzlucky
Rotzlucky

Reputation: 117

renameTo should actually do what you want. I use it too in my project as you can see in this question: Play: How to prevent 404 on image src on first request after upload

File movedFile = new File("/var/www/public/", "filename.jpg");
file.renameTo(movedFile);

That's how I use it. There shouldn't be a difference in the other Constructor is use. But from your question it isn't clear what is wrong on your side.

Also: note that moving a file to /public might not work on a production environment as you expect. When you do a production build everything in public is packaged in to a .jar file. Files uploaded at runtime should be moved to an external location

Upvotes: 0

jacks
jacks

Reputation: 4753

The use of /tmp (on applicable OS's) is a convention for compatibility since it's writable by all users and not just administrative users.

In my own upload projects I generally make a copy of the file into whatever path I want it and then delete the temporary file:-

Files.copy(file.toPath(), Paths.get("/my/apps/file/store/path/", ("copy_" + name)), REPLACE_EXISTING)
Files.deleteIfExists(file.toPath)

Upvotes: 2

Related Questions