Java实现的图片上传工具类完整实例
程序员文章站
2024-04-02 09:47:52
本文实例讲述了java实现的图片上传工具类。分享给大家供大家参考,具体如下:
package com.gcloud.common;
import javax.i...
本文实例讲述了java实现的图片上传工具类。分享给大家供大家参考,具体如下:
package com.gcloud.common; import javax.imageio.imageio; import java.awt.image.bufferedimage; import java.io.*; /** * 图片上传工具类 * created by charlin on 2017/9/10. */ public class uploadimageutil { private string filetype; private long maxsize; private long width; private long height; public uploadimageutil() { } public uploadimageutil(string filetype, long maxsize, long width, long height) { this.filetype = filetype; this.maxsize = maxsize; this.width = width; this.height = height; } /** * 检查上传图像大小 * * @param upload * @param uploadfilename * @param uploadcontenttype * @return */ public string checkuploadimage(file upload, string uploadfilename, string uploadcontenttype) { try { if (filetype != null) { string[] filetypes = filetype.split(","); int count = 0; for (int i = 0; i < filetypes.length; i++) { if (uploadcontenttype.equals(filetypes[i])) { count++; continue; } } if (count == 0) { return "您上传的文件类型不对!"; } } bufferedimage bi = imageio.read(upload); int w = bi.getwidth(); int h = bi.getheight(); if (w > width || h > height) { return "上传照片宽度和高度不符合要求"; } if (upload.length() > maxsize) { return "上传照片过大"; } } catch (ioexception e) { e.printstacktrace(); } return null; } /** * 图片上传 * * @param upload * @param uploadfilename * @param path * @return * @throws exception */ public void uploadimage(file upload, string uploadfilename, string path) throws exception { inputstream is = null; outputstream os = null; try { is = new fileinputstream(upload); file f = new file(path); if (!f.exists()) f.mkdirs(); os = new fileoutputstream(path + "/" + uploadfilename); byte buffer[] = new byte[1024]; int count = 0; int flag = 0; while ((count = is.read(buffer)) > 0) { os.write(buffer, 0, count); } } catch (filenotfoundexception e) { } catch (ioexception e) { file f = new file(path + "/" + uploadfilename); if (f.exists()) { f.delete(); } } finally { try { os.close(); is.close(); } catch (ioexception ioe) { } } } /** * 清除文件 * @param path */ public void clear(string path) { file file = new file(path); if (file.isfile() && file.exists()) { file.delete(); } } public string getfiletype() { return filetype; } public void setfiletype(string filetype) { this.filetype = filetype; } public long getmaxsize() { return maxsize; } public void setmaxsize(long maxsize) { this.maxsize = maxsize; } public long getwidth() { return width; } public void setwidth(long width) { this.width = width; } public long getheight() { return height; } public void setheight(long height) { this.height = height; } }
更多java相关内容感兴趣的读者可查看本站专题:《java图片操作技巧汇总》、《java日期与时间操作技巧汇总》、《java操作dom节点技巧总结》、《java文件与目录操作技巧汇总》及《java数据结构与算法教程》。
希望本文所述对大家java程序设计有所帮助。