Java implementation file upload download and image compression code samples
- 2020-04-01 03:45:27
- OfStack
To share a project used to upload to the file download and the compression of the image, directly from the project :)
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);
/**
* Upload the file to the 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;
}
/**
* Upload the picture
* @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);
}
}
//Compressed image
if(x!=null&&!"".equals(x) && y!=null&&!"".equals(y)) {
saveFileName = thumbnailatorImage(imagePath, fileName, type, Integer.parseInt(x), Integer.parseInt(y));
}
}
return saveFileName;
}
/**
* Upload and share pictures
* @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)) {
//Share upload image path
imagePath = "/upload/articleimage/";
}else if("5".equals(type)) {
//Link upload image path
imagePath = "/upload/linkimage/";
} else {
//Avatar upload image path
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);
}
//Compressed image
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;
}
/**
* Upload compress and save the picture
* @param oldSavePath Original file path
* @param oldFileName Original file name
* @param fix The file type
* @param x The width that needs to be compressed
* @param y Length of compression required
* @return
* @throws IOException
*/
public static String thumbnailatorImage(String oldSavePath,String oldFileName,String fix,int x,int y) throws IOException {
//Thumbnail Read and Compressed image
BufferedImage waterMarkBufferedImage = Thumbnails.of(oldSavePath+oldFileName)
//Thumbnail The method of ,Compressed image
.size(x, y)
//Read as BufferedImage object & NBSP; < br / >
.asBufferedImage();
//Writes an image from memory to a specified file & NBSP; < br / >
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;
}
/**
* Download the zip and save the image
* @param oldSavePath Original file path
* @param oldFileName Original file name
* @param fix The file type
* @param x The width that needs to be compressed
* @param y Length of compression required
* @return
* @throws IOException
*/
public static String downloadThumbnailatorImage(String servicePath,String uri,int x,int y) throws IOException {
//Verify that the image is
String uriSubPath = uri.substring(0, uri.lastIndexOf("/")+1);//Before file name, after server
String fileName = uri.substring(uri.lastIndexOf("/")+1,uri.length());//File name
String getThumbnailatorPath = servicePath + uriSubPath+x+"-"+y+"/";
String saveFileName = getThumbnailatorPath+fileName;
File downFilePath = new File(getThumbnailatorPath);//Compressed folder
File downFile = new File(saveFileName);//Compressed file
if (downFilePath.isDirectory()&&downFile.exists()) {
return saveFileName;
} else {
//Thumbnail Read and Compressed image
log.error(servicePath+uri);
BufferedImage waterMarkBufferedImage = Thumbnails.of(servicePath+uri)
//Thumbnail The method of ,Compressed image
.size(x, y)
//Read as BufferedImage object & NBSP; < br / >
.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;
}
}
That's all I've Shared with you in this article.