Java实现的图片上传工具类完整实例
本文实例讲述了Java实现的图片上传工具类。分享给大家供大家参考,具体如下:
packagecom.gcloud.common; importjavax.imageio.ImageIO; importjava.awt.image.BufferedImage; importjava.io.*; /** *图片上传工具类 *Createdbycharlinon2017/9/10. */ publicclassUploadImageUtil{ privateStringfileType; privateLongmaxSize; privateLongwidth; privateLongheight; publicUploadImageUtil(){} publicUploadImageUtil(StringfileType,LongmaxSize,Longwidth,Longheight){ this.fileType=fileType; this.maxSize=maxSize; this.width=width; this.height=height; } /** *检查上传图像大小 * *@paramupload *@paramuploadFileName *@paramuploadContentType *@return */ publicStringcheckUploadImage(Fileupload,StringuploadFileName,StringuploadContentType){ try{ if(fileType!=null){ String[]fileTypes=fileType.split(","); intcount=0; for(inti=0;iwidth||h>height){ return"上传照片宽度和高度不符合要求"; } if(upload.length()>maxSize){ return"上传照片过大"; } }catch(IOExceptione){ e.printStackTrace(); } returnnull; } /** *图片上传 * *@paramupload *@paramuploadFileName *@parampath *@return *@throwsException */ publicvoiduploadImage(Fileupload,StringuploadFileName,Stringpath)throwsException{ InputStreamis=null; OutputStreamos=null; try{ is=newFileInputStream(upload); Filef=newFile(path); if(!f.exists())f.mkdirs(); os=newFileOutputStream(path+"/"+uploadFileName); bytebuffer[]=newbyte[1024]; intcount=0; intflag=0; while((count=is.read(buffer))>0){ os.write(buffer,0,count); } }catch(FileNotFoundExceptione){ }catch(IOExceptione){ Filef=newFile(path+"/"+uploadFileName); if(f.exists()){ f.delete(); } }finally{ try{ os.close(); is.close(); }catch(IOExceptionioe){ } } } /** *清除文件 *@parampath */ publicvoidclear(Stringpath){ Filefile=newFile(path); if(file.isFile()&&file.exists()){ file.delete(); } } publicStringgetFileType(){ returnfileType; } publicvoidsetFileType(StringfileType){ this.fileType=fileType; } publicLonggetMaxSize(){ returnmaxSize; } publicvoidsetMaxSize(LongmaxSize){ this.maxSize=maxSize; } publicLonggetWidth(){ returnwidth; } publicvoidsetWidth(Longwidth){ this.width=width; } publicLonggetHeight(){ returnheight; } publicvoidsetHeight(Longheight){ this.height=height; } }
更多java相关内容感兴趣的读者可查看本站专题:《Java图片操作技巧汇总》、《java日期与时间操作技巧汇总》、《Java操作DOM节点技巧总结》、《Java文件与目录操作技巧汇总》及《Java数据结构与算法教程》。
希望本文所述对大家java程序设计有所帮助。