layui上传图片到servlet后台处理,并且压缩图片
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8"); // 设置编码
System.out.println("上传照片");
String id= request.getParameter("ID");
System.out.println(id);
JSONObject jsonobj = new JSONObject();
int returnTag = -1;
String saveName=null;
//上传的文件名
String filename=null;
try {
// 获得磁盘文件条目工厂
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setRepository(new File(TEMP_FOLDER));
// 设置 缓存的大小,当上传文件的容量超过该缓存时,直接放到 暂时存储室
factory.setSizeThreshold(1024 * 1024);
// 高水平的API文件上传处理
ServletFileUpload upload = new ServletFileUpload(factory);
// 可以上传多个文件
List
System.out.println("list==="+list);
// 获取上传的文件
String base64 = "";
for (FileItem file : list) {
FileItem item = file;
// 获取文件名
filename = getUploadFileName(item);
if(filename == null){
}else{
String suffix = filename.substring(filename.lastIndexOf(".") + 1);
System.out.println("文件格式===="+suffix);
System.out.println("获取的文件后缀名=========================" + suffix);
String[] regular = { "JPG", "GIF","PNG","JPEG" ,"BMP"};
boolean flag = false;
// 保存后的文件名
saveName = new Date().getTime() + filename.substring(filename.lastIndexOf("."));
item.write(new File(PATH_FOLDER, saveName));
//判断文件格式是否是图片
for (String str : regular) {
if (suffix.equalsIgnoreCase(str)) {
flag = true;
}
}
if (flag) {
long length = new File(PATH_FOLDER+"/"+saveName).length();
System.out.println(length);
if (length / 1048576 >= 0.5) {// 如果图片大于等于0.5MB 则按80%缩小
try {
zoom(PATH_FOLDER+"/"+saveName,PATH_FOLDER+"/"+saveName, length, 0.5);
} catch (IOException e) {
System.out.println("出错啦:" + e);
}
}
}
// base64
base64 = encodeBase64File(PATH_FOLDER+"/"+saveName);
System.out.println(base64);
System.out.println("luuuuuuuuuuuuuuuuuuuu="+PATH_FOLDER+"/"+saveName);
}
}
if (returnTag != -1) {
// 请求失败
jsonobj.put("STATUS", "1");
} else {
jsonobj.put("code", 0);
}
response.getWriter().write(jsonobj.toString());
}catch (Exception e) {
System.out.println("出错啦");
e.printStackTrace();
jsonobj.put("errorCode", 0);
response.getWriter().write(jsonobj.toString());
response.getWriter().close();
}
}
private String getUploadFileName(FileItem item) {
// 获取路径名
String value = item.getName();
if(value == null){
return null;
}else{
// 索引到最后一个反斜杠
int start = value.lastIndexOf("/");
// 截取 上传文件的 字符串名字,加1是 去掉反斜杠,
String filename = value.substring(start + 1);
return filename;
}
}
public void init(ServletConfig config) throws ServletException {
ServletContext servletCtx = config.getServletContext();
// 初始化路径
// 缩略图保存路径
PATH_FOLDER = "F:/file";
//PATH_FOLDER = "/apache-tomcat-7.0.63/img";
System.out.println("保存缩略图的目录===========" + PATH_FOLDER);
// 存放临时文件的目录,存放xxx.tmp文件的目录
TEMP_FOLDER = servletCtx.getRealPath("/temp");
System.out.println("存放临时文件的目录===========" + TEMP_FOLDER);
File dir = new File(PATH_FOLDER);
if (!dir.isDirectory()) {
dir.mkdir();
}
File dir2 = new File(TEMP_FOLDER);
if (!dir2.isDirectory()) {
dir2.mkdir();
}
}
/**
* 获取参数
* @param request
* @return
*/
private String getParams(HttpServletRequest request){
StringBuilder param = new StringBuilder();
try{
BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream(),"utf-8"));
String line = null;
while((line=br.readLine())!=null){
param.append(line);
}
}catch (Exception e) {
e.printStackTrace();
}
return param.toString();
}
public static String encodeBase64File(String path) throws Exception {
System.out.println("开始执行");
File file = new File(path);
FileInputStream inputFile = new FileInputStream(file);
byte[] buffer = new byte[(int)file.length()];
inputFile.read(buffer);
inputFile.close();
return new BASE64Encoder().encode(buffer);
}
public static void main(String[] args) {
//Random random = new Random();
//System.out.print(random.nextInt(100));
String fullPath="F://file/1568086981813.jpg";
String newPath="F://file/image/1568086981813.jpg";
long length = new File(fullPath).length();
if (length / 1048576 >= 0.5) {// 如果图片大于等于0.5MB 则按80%缩小
try {
zoom(fullPath, newPath, length, 0.5);
} catch (IOException e) {
System.out.println("出错啦:" + e);
}
}
String base64Str;
try {
base64Str = encodeBase64File(newPath);
//System.out.println("base64Str===" + base64Str);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//String newPath = Base64Util.getBase64Str(newPath);
}
// 缩图
public static void zoom(String oldFile, String zoomFile,long length,double newRate) throws IOException {
DecimalFormat df = new DecimalFormat("0.00");// 设置保留位数
double rate=0.8;
System.out.println("原始图片大小:" + df.format((float) length / mb) + "MB");
long newfile = new File(oldFile).length();
int i = 1;
// 如果首次压缩还大于2MB则继续处理
while ((float) newfile / mb >= newRate) {
System.out.println("压缩后图片大小:" + newfile);
rate = rate - 0.05;// 暂定按照0.03频率压缩
System.out.println(i + " rate=" + rate);
BufferedImage srcImage = ImageIO.read(new File(oldFile));
int WIDTH = (int) (srcImage.getWidth() * rate);
int HEIGHT = (int) (srcImage.getHeight() * rate);
BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
g.drawImage(srcImage, 0, 0, WIDTH, HEIGHT, null);
// 缩小
ImageIO.write(image, "jpg", new File(zoomFile));
i++;
newfile = new File(zoomFile).length();
System.out.println("压缩次数:" + i);
}
// 调整方向
BufferedImage newImage = ImageIO.read(new File(zoomFile));
ImageIO.write(newImage, "jpg", new File(zoomFile));
System.out.println("处理后图片路径:" + zoomFile + ";缩小之后大小:"
+ df.format((float) new File(zoomFile).length() / mb) + "MB");
}
}