java webå¼åä¸ï¼ä½¿ç¨æ件æä½ç±»æ¥ä¸ä¼ å¾ç并读åï¼å¦ä¸ä»£ç ï¼
* @desc: å¾çå¤çå·¥å
·
* @author: bingye
* @createTime: 2015-3-17 ä¸å04:25:32
* @version: v1.0
*/
public class ImageUtil {
/**
* å°å¾çåå°å®¢æ·ç«¯
* @author: bingye
* @createTime: 2015-3-17 ä¸å04:36:04
* @history:
* @param image
* @param response void
*/
public static void writeImage(byte[] image,HttpServletResponse response){
if(image==null){
return;
}
byte[] buffer=new byte[1024];
InputStream is=null;
OutputStream os=null;
try {
is=new ByteArrayInputStream(image);
os=response.getOutputStream();
while(is.read(buffer)!=-1){
os.write(buffer);
os.flush();
}
} catch (IOException e) {
e.printStackTrace();
} finally{
try {
if(is!=null){is.close();}
if(os!=null){os.close();}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* è·åæå®è·¯å²å¾ç
* @author: bingye
* @createTime: 2015-3-21 ä¸å10:50:44
* @param filePath
* @param response void
*/
public static void writeImage(String filePath,HttpServletResponse response){
File imageFile=new File(filePath);
if(imageFile!=null && imageFile.exists()){
byte[] buffer=new byte[1024];
InputStream is=null;
OutputStream os=null;
try {
is=new FileInputStream(imageFile);
os=response.getOutputStream();
while(is.read(buffer)!=-1){
os.write(buffer);
os.flush();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally{
try {
if(is!=null){is.close();}
if(os!=null){os.close();}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* å¾çä¸ä¼ å°æ件夹
* @author: bingye
* @createTime: 2015-3-20 ä¸å08:07:25
* @param file
* @param savePath
* @return boolean
*/
public static ResultDto uploadToLocal(CommonsMultipartFile file,String savePath){
if(file!=null && !file.isEmpty()){
//è·åæ件å称
String fileName=file.getOriginalFilename();
//è·ååç¼å
String suffixName=fileName.substring(fileName.indexOf(".")+1);
//æ°å称
String newFileName=System.currentTimeMillis()+"."+suffixName;
//æ°æ件路å²
String filePath=savePath+newFileName;
//è·ååå¨æ件路å¾
File fileDir=new File(savePath);
if(!fileDir.exists()){
//å¦ææ件夹没æï¼æ°å»º
fileDir.mkdirs();
}
FileOutputStream fos=null;
try {
fos=new FileOutputStream(filePath);
fos.write(file.getBytes());
fos.flush();
return ResultUtil.success("UPLOAD_SUCCESS", URLEncoder.encode(newFileName,"utf-8"));
} catch (Exception e) {
e.printStackTrace();
return ResultUtil.fail("UPLOAD_ERROR");
} finally{
try {
if(fos!=null){
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
return ResultUtil.fail("UPLOAD_ERROR");
}
}
}
return ResultUtil.fail("UPLOAD_ERROR");
}
}