「Java開発」ファイルのアップロード、画像圧縮を実現する
package com.eabax.plugin.yundada.utils;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.eabax.plugin.yundada.GaContext;
public class FileUploadDownloadUtil {
private static final Logger log = LoggerFactory.getLogger(FileUploadDownloadUtil.class);
/**
* Serverにファイルをアップロード
* @param request
* @param type
* @return
* @throws Exception
*/
public static String upload(HttpServletRequest request, String type) throws Exception {
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
String saveFileName = null;
if (isMultipart) {
String savePath = request.getSession().getServletContext()
.getRealPath(“/")
+ “/upload/";
String tempPath = request.getSession().getServletContext()
.getRealPath(“/")
+ “/upload/temp/";
File saveFile = new File(savePath);
File tempFile = new File(tempPath);
if (!saveFile.isDirectory())
saveFile.mkdirs();
if (!tempFile.isDirectory())
tempFile.mkdirs();
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(1024 * 4);
factory.setRepository(tempFile);
ServletFileUpload uploader = new ServletFileUpload(factory);
uploader.setSizeMax(20 * 1024 * 1024);
List<FileItem> fileItems = uploader.parseRequest(request);
for (FileItem item : fileItems) {
if (item.isFormField()) {
// funName=item.getString();
} else {
// String fileName=item.getName();
// String
// fix=fileName.substring(fileName.lastIndexOf(“.")+1);
String fix = type;
Date nowDate = new Date();
SimpleDateFormat sdf = new SimpleDateFormat(
“yyyyMMddhhmmss");
String fileName = sdf.format(nowDate);
fileName += System.currentTimeMillis();
fileName += “." + fix;
saveFileName = “/upload/" + fileName;
File file = new File(savePath + fileName);
item.write(file);
}
}
}
return saveFileName;
}
/**
* 画像のアップロード
* @param request
* @param type
* @return
* @throws Exception
*/
public static String uploadHeadShow(HttpServletRequest request,GaContext context, String type) throws Exception {
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
String saveFileName = null;
String imagePath = “/upload/headshow/";
String x = request.getParameter(“length");
String y = request.getParameter(“wide");
if (isMultipart) {
String headShowServicePath = request.getSession().getServletContext()
.getRealPath(“/")
+ imagePath;
Date nowDate = new Date();
SimpleDateFormat sdf = new SimpleDateFormat(
“yyyyMMddhhmmss");
String fileName = context.getUsername()+sdf.format(nowDate);
File headShowFile = new File(headShowServicePath);
if (!headShowFile.isDirectory())
headShowFile.mkdirs();
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(1024 * 4);
factory.setRepository(headShowFile);
ServletFileUpload uploader = new ServletFileUpload(factory);
uploader.setSizeMax(20 * 1024 * 1024);
List<FileItem> fileItems = uploader.parseRequest(request);
for (FileItem item : fileItems) {
if (item.isFormField()) {
// funName=item.getString();
} else {
String fix = type;
fileName += “." + fix;
saveFileName = imagePath + fileName;
File file = new File(headShowServicePath + fileName);
item.write(file);
}
}
//画像圧縮
if(x!=null&&!"".equals(x) && y!=null&&!"".equals(y)) {
saveFileName = thumbnailatorImage(imagePath, fileName, type, Integer.parseInt(x), Integer.parseInt(y));
}
}
return saveFileName;
}
/**
* 写真をアップロードして共有
* @param request
* @param type
* @return
* @throws Exception
*/
public static JSONObject uploadArticleImage(HttpServletRequest request,GaContext context, String type) throws Exception {
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
JSONObject saveFileName = new JSONObject();
String imagePath = “";
String x = request.getParameter(“length");
String y = request.getParameter(“wide");
if(“4".equals(type)) {
//写真アップロードのパス
imagePath = “/upload/articleimage/";
}else if(“5".equals(type)) {
//画像パスのリンク
imagePath = “/upload/linkimage/";
} else {
//画像アップロードパス
imagePath = “/upload/headshow/";
}
if (isMultipart) {
String headShowServicePath = request.getSession().getServletContext()
.getRealPath(“/")
+ imagePath;
File headShowFile = new File(headShowServicePath);
if (!headShowFile.isDirectory())
headShowFile.mkdirs();
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(1024 * 4);
factory.setRepository(headShowFile);
ServletFileUpload uploader = new ServletFileUpload(factory);
uploader.setSizeMax(20 * 1024 * 1024);
List<FileItem> fileItems = uploader.parseRequest(request);
for (FileItem item : fileItems) {
UUID uuid = UUID.randomUUID();
String fileName = uuid.toString();
if (item.isFormField()) {
// funName=item.getString();
} else {
String fix = type;
fileName += “." + fix;
saveFileName.put( uuid.toString(),imagePath + fileName);
File file = new File(headShowServicePath + fileName);
item.write(file);
}
//画像圧縮
if(x!=null&&!"".equals(x) && y!=null&&!"".equals(y)) {
String thumbnailatorName = thumbnailatorImage(imagePath, fileName, type, Integer.parseInt(x), Integer.parseInt(y));
saveFileName.put(“thumbnailatorImage", thumbnailatorName);
}
}
}
return saveFileName;
}
/**
* 圧縮画像をアップロードして保存
* @param oldSavePath
* @param oldFileName 原文件名称
* @param fix ファイルタイプ
* @param x 幅
* @param y 長さ
* @return
* @throws IOException
*/
public static String thumbnailatorImage(String oldSavePath,String oldFileName,String fix,int x,int y) throws IOException {
BufferedImage waterMarkBufferedImage = Thumbnails.of(oldSavePath+oldFileName)
.size(x, y)
.asBufferedImage();
String savePath = oldSavePath+x+"-“+y+"/";
File saveFile = new File(savePath);
if (!saveFile.isDirectory())
saveFile.mkdirs();
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(1024 * 4);
factory.setRepository(saveFile);
ServletFileUpload uploader = new ServletFileUpload(factory);
uploader.setSizeMax(20 * 1024 * 1024);
UUID uuid = UUID.randomUUID();
String fileName = uuid.toString();
fileName += “." + fix;
String saveFileName = savePath+fileName;
File fileOutPut = new File(saveFileName);
ImageIO.write(waterMarkBufferedImage, fix, fileOutPut);
return saveFileName;
}
public static String downloadThumbnailatorImage(String servicePath,String uri,int x,int y) throws IOException {
String uriSubPath = uri.substring(0, uri.lastIndexOf(“/")+1);
String fileName = uri.substring(uri.lastIndexOf(“/")+1,uri.length());
String getThumbnailatorPath = servicePath + uriSubPath+x+"-“+y+"/";
String saveFileName = getThumbnailatorPath+fileName;
File downFilePath = new File(getThumbnailatorPath);
File downFile = new File(saveFileName);
if (downFilePath.isDirectory()&&downFile.exists()) {
return saveFileName;
} else {
log.error(servicePath+uri);
BufferedImage waterMarkBufferedImage = Thumbnails.of(servicePath+uri)
.size(x, y)
.asBufferedImage();
if (!downFilePath.isDirectory()) {
downFilePath.mkdirs();
}
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(1024 * 4);
factory.setRepository(downFilePath);
ServletFileUpload uploader = new ServletFileUpload(factory);
uploader.setSizeMax(20 * 1024 * 1024);
File fileOutPut = new File(saveFileName);
ImageIO.write(waterMarkBufferedImage, “jpg", fileOutPut);
}
return saveFileName;
}
}