java 上传图片

public String uploadPic() {
  String path = ServletActionContext.getServletContext().getRealPath("/");
  BufferedInputStream bis = null;
  BufferedOutputStream bos = null;
  InputStream streamIn = null; // 定义输入流的引用
  OutputStream streamOut = null; // 定义输出流的引用
  try {
   streamIn = new FileInputStream(file1);
   bis = new BufferedInputStream(streamIn);
   Date  date=new Date();
   Calendar cal=Calendar.getInstance();//使用日历类
   String year=String.valueOf(cal.get(Calendar.YEAR));
   String month=String.valueOf(cal.get(Calendar.MONTH)+1);
   DateFormat format = new SimpleDateFormat("yyyy.MM.dd");
   String date_str=format.format(new Date());
   fileImage= new File(path+"images/"+year+"/"+month+"/"+date_str);
   if(!fileImage.exists()){
    fileImage.mkdirs();
   }
   String imagePath=fileImage.getPath()+"/"+file1FileName;
   fileImage =new File(imagePath);
   if(fileImage.exists()){
    System.out.println("此图片已经存在,请更改图片名称");
    return "此图片已经存在,请更改图片名称";
   }
   streamOut = new FileOutputStream(imagePath); // 新建输出流对象
   bos = new BufferedOutputStream(streamOut);
   int bytesRead = 0;
   byte[] buffer = new byte[1024 * 1024];
   // 开始保存文件
   while ((bytesRead = bis.read(buffer)) != -1) {
    //把读取进来的数据保存到缓冲区,然后再输出到文件中
    bos.write(buffer, 0, bytesRead);
    bos.flush();
   }
   streamOut.close();
   streamIn.close(); // 关闭流
   
  } catch (Exception e) {
   log.error("uploadPicAction.uploadPic  error:\n"+Util.exceptionToString(e));
  }
  return null;

posted @ 2012-07-23 18:50  淡泊名利  阅读(227)  评论(0)    收藏  举报