文件流的读写操作从硬盘中读取

来源:互联网 发布:星星知我心歌词 编辑:程序博客网 时间:2024/05/20 21:48
写: 

/**
  * 上传用户照片
  *
  * @param request
  * @return
  * @throws Exception
  */
 public List uploadUserPic(HttpServletRequest request) throws Exception {
  List result = new ArrayList();
  DiskFileItemFactory dfiFactory = new DiskFileItemFactory();
  ServletFileUpload sfUpload = new ServletFileUpload(dfiFactory);
  sfUpload.setHeaderEncoding("GBK");
  List fileItems = sfUpload.parseRequest(request);
     String outPath = "";
  int bytesRead = 0;
  byte[] buffer = null;
  InputStream ins = null;
  OutputStream os = null;
  // 工程类路径,用来获取保存头像的路径
  String url = request.getSession().getServletContext().getRealPath(
    request.getRequestURI());
  int a = url.lastIndexOf(File.separator);
  url = url.substring(0, a);
  StringBuffer dirPath = new StringBuffer(url).append(File.separator)
    .append("headPicture");

  while (iter.hasNext()) {
   AttachmentVO attachmentVO = new AttachmentVO();
   FileItem fileItem = (FileItem) iter.next();
   if (!fileItem.isFormField()) {
    // 浏览的路径
    filePath = fileItem.getName();
    if (filePath != null && StringUtil.notEmpty(filePath)) {

     // 创建文件夹headPicture
     File fpath = new File(dirPath.toString());
     if (!fpath.exists()) {
      fpath.mkdir();
     }

     // 创建某个用户的图片文件夹
     dirPath.append("/").append(userVO.getCode());
     fpath = new File(dirPath.toString());
     // 如果用户文件夹不存在,则创建用户文件夹
     if (!fpath.exists()) {
      fpath.mkdir();
     } else {
      // 调用删除文件夹及文件夹的内容方法
      deleteAll(fpath);
      fpath.mkdir();
     }

     // 获取图片的名字
     fileName = filePath
       .substring(filePath.lastIndexOf("\\") + 1);
     dirPath.append("/");
     outPath = dirPath.toString() + fileName;
     if (!"".equals(filePath)) {
      ins = fileItem.getInputStream();
      os = new FileOutputStream(outPath);
      bytesRead = 0;
      buffer = new byte[4096];
      while ((bytesRead = ins.read(buffer, 0, 4096)) != -1) {
       os.write(buffer, 0, bytesRead);
      }
      buffer = null;
      os.close();
      ins.close();
     }
     fileSize = fileItem.getSize();
     if (fileSize > 102400) {
      throw new Exception(fileName + "文件大小不能超过100K");
     }
     extend1 = fileName.substring(fileName.lastIndexOf("."));
     if (!".jpg".equals(extend1) && !".JPG".equals(extend1)
       && !".GIF".equals(extend1)
       && !".gif".equals(extend1)) {
      throw new Exception("只能上传jpg或gif格式图片");
     }
     byte[] bytes = new byte[12];
     attachmentVO.setCreatorIP(getIpAddr(request));
     attachmentVO.setExtend(extend1);
     attachmentVO.setFileSize(fileSize);
     attachmentVO.setCreateTime(new Date());
     attachmentVO.setContexts(bytes);
     if (StringUtil.notEmpty(attachmentId)) {
      attachmentVO.setRelationId(attachmentId);
     } else {
      attachmentVO.setRelationId("");
     }
     attachmentVO.setFilePath("/headPicture/" + userVO.getCode()
       + "/" + fileName);
     attachmentVO.setName(fileName);
     attachmentVO.setCreatorId(TLAppUtil.getCurrUserId(request));
     attachmentVO.setCreatorOrgId(TLAppUtil
       .getCurrOrgId(request));
     name = fileItem.getFieldName();
     if ("userPic".equals(name)) {
      attachmentVO.setType(FileTypeEnum.USERPIC);
     } else {
      attachmentVO.setType("");
     }
     result.add(attachmentVO);
     // is.close();
    }
  // -------------------------------------------------------------------------

删除文件夹的方法

 /**
  * 删除硬盘中文件夹中的方法
  *
  * @param f
  */
 public static void deleteAll(File f) {
  // 文件
  if (f.isFile()) {
   f.delete();
  } else { // 文件夹
   // 获得当前文件夹下的所有子文件和子文件夹
   File f1[] = f.listFiles();
   // 循环处理每个对象
   int len = f1.length;
   for (int i = 0; i < len; i++) {

    // 递归调用,处理每个文件对象
    deleteAll(f1[i]);
   }
   // 删除当前文件夹
   f.delete();
  }
 }

 

 

======================================

从硬盘读取数据


 /**
  * 读取附件
  * @param mapping
  * @param form
  * @param request
  * @param response
  * @return
  * @throws Exception
  */
 public ActionForward readUserPic(ActionMapping mapping, ActionForm form,
   HttpServletRequest request, HttpServletResponse response) throws Exception
 {
  UserBusIface service = (UserBusIface) this.getObject();
  String id = request.getParameter("id");
  File uploadFile =null;
  if (StringUtil.notEmpty(id))
  {
   
   String bytes= service.getUserPic(id, FileTypeEnum.USERPIC);
            //工程类路径,用来获取保存头像的路径
   String url = request.getSession().getServletContext().getRealPath(
     request.getRequestURI());
   int a = url.lastIndexOf(File.separator);
   url = url.substring(0, a);
   
   //读取数据库中的filepath路径
   
   BufferedInputStream bis = null;
   BufferedOutputStream bos = null;
   OutputStream fos = null;
   InputStream fis = null;

   // 如果是从服务器上取就用这个获得系统的绝对路径方法。
             //String filepath =servlet.getServletContext().getRealPath("/" + path);
   
   String filepath = bytes;
   if(filepath.equals("noup.jpg")){
     uploadFile = new File(url+"/images/Supply/noUp.jpg");
   }else{
        uploadFile = new File(url+filepath);
   }
   fis = new FileInputStream(uploadFile);
   bis = new BufferedInputStream(fis);
   fos = response.getOutputStream();
   bos = new BufferedOutputStream(fos);
   // 这个就就是弹出下载对话框的关键代码
   //response.setHeader("Content-disposition", "attachment;filename="
    // + URLEncoder.encode(bytes, "utf-8"));
   int bytesRead = 0;
   // 用输入流进行先读,然后用输出流去写
   byte[] buffer = new byte[8192];
   while ((bytesRead = bis.read(buffer, 0, 8192)) != -1) {
    bos.write(buffer, 0, bytesRead);
   }
   bos.flush();
   fis.close();
   bis.close();
   fos.close();
   bos.close();
  
  }
  return null;
 }

 

 

原创粉丝点击