Java tutorial
/********************************************************************************* * * Copyright 2014 BOUSSEJRA Malik Olivier, HALDEBIQUE Geoffroy, ROYER Johan * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ********************************************************************************/ package functions; import java.io.File; import java.io.IOException; import models.Image; import org.apache.commons.io.FileUtils; import play.Play; import play.mvc.Http.MultipartFormData.FilePart; public class UploadImage { /** * Upload une image sur le serveur. * Vrifie au pralable que c'est bien un fichier image. * @param filePart : l'image uploader * @return l'image si l'image est valide, null sinon */ public static Image upload(FilePart filePart) throws IOException { if (isImage(filePart)) { File image = filePart.getFile(); String fileName = filePart.getFilename(); Image i = new Image(fileName); String path = Play.application().configuration().getString("image.path") + i.image_chemin; File destinationFile = new File(path); FileUtils.copyFile(image, destinationFile); i.save(); return i; } else return null; } /** * Vrifie que le fichier est bien une image * @param filePart : le fichier que l'on teste * @return VRAI ou FAUX */ private static boolean isImage(FilePart filePart) { if (filePart != null) { return filePart.getContentType().startsWith("image"); } else { return false; } } }