Skip to content

Instantly share code, notes, and snippets.

@FWidm
Created March 1, 2017 14:14
Show Gist options
  • Save FWidm/0667a5b40c023f34d401d7144fd6bd0e to your computer and use it in GitHub Desktop.
Save FWidm/0667a5b40c023f34d401d7144fd6bd0e to your computer and use it in GitHub Desktop.
@Security.Authenticated(ActionAuthenticator.class)
public Result upload() {
Logger.debug("upload!");
Http.MultipartFormData<File> body = request().body().asMultipartFormData();
Http.MultipartFormData.FilePart<File> picture = body.getFile("picture");
Logger.debug("picture="+picture);
if (picture != null) {
String fileName = picture.getFilename();
String contentType = picture.getContentType();
String fileType = determineFileType(fileName);
if (contentType.contains("image")) {
File pictureFile = picture.getFile();
Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
File directoryFile = new File("/var/www/html/img/" + year + "/" + month + "/");
directoryFile.mkdirs();
try {
directoryFile = File.createTempFile("img", "." + fileType, directoryFile);
Files.write(directoryFile.toPath(), Files.readAllBytes(pictureFile.toPath()));
} catch (IOException e) {
return internalServerError(JsonUtil.prepareJsonStatus(INTERNAL_SERVER_ERROR, "Could not place file on the server"));
}
Logger.debug("Filepath:" + directoryFile.toPath());
int i = 0;
String host = "http://" + request().host();
i = host.lastIndexOf(":");
host = host.substring(0, i);
String url = host + getUrl(directoryFile.toPath(), "img");
try {
UploadedMedia mediaRecord = new UploadedMedia(new URI(url), UserRepository.findUserByEmail(request().username()), contentType);
Logger.debug("Uploaded file=" + mediaRecord);
mediaRecord.save();
return created(JsonUtil.toJson(mediaRecord));
} catch (URISyntaxException e) {
e.printStackTrace();
Logger.error(e.getMessage());
}
}
else
Logger.debug("contenttype does not contain image!");
}
else
Logger.debug("picture is null!");
return badRequest(JsonUtil.prepareJsonStatus(BAD_REQUEST, "Request did not contain a 'picture' key or valid picture."));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment