zoukankan      html  css  js  c++  java
  • java blob 文件上传下载

    1、文件上传

    pojo中为byte[] 类型,数据库中对应为blob类型。

    主要代码:

    FileInputStream fis = null;
    
    fis = new FileInputStream(new File(filePath));
    byte[] inputByte = input2byte(fis);
    fileBean.setContent(inputByte);
    
    /**
    * 将 流 转换为byte
    * @param inStream
    * @return
    * @throws IOException
    */
    public static final byte[] input2byte(InputStream inStream) throws IOException { 
      ByteArrayOutputStream swapStream = null;
      try {
        swapStream = new ByteArrayOutputStream();
        byte[] buff = new byte[1024]; 
        int rc = 0; 
        while ((rc = inStream.read(buff, 0, 1024)) > 0) { 
          swapStream.write(buff, 0, rc); 
        } 
        return swapStream.toByteArray();
      } catch (Exception e) {
        logger.info(e.getStackTrace());
      } finally {
        if (swapStream != null) {
        safeClose(swapStream);
        }
      }
      return null;
    } 

    2、文件下载

    @Override
    public void downFileByBlob(HttpServletRequest request, HttpServletResponse response, String fileId) throws IOException {
      AtFileupload bean = hibernateDao.getObject(AtFileupload.class, fileId);
      if (bean.getContent() != null) {
        String filename= bean.getFileName();//获取日志中存储的文件名称
        String userAgent = request.getHeader("user-agent").toLowerCase(); 
        if (userAgent.contains("msie") || userAgent.contains("like gecko")) { 
        // IE 
          filename = URLEncoder.encode(filename, "UTF-8"); 
        } else { 
        // 非IE 
          filename = new String(filename.getBytes("UTF-8"), "iso-8859-1"); 
        } 
        try {
          byte[] fileStream = bean.getContent();
          // 以流的形式下载文件
            response.setContentType("application/x-msdownload");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-Disposition", "attachment; filename=" + filename);
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            toClient.write(fileStream);
            toClient.flush();
            toClient.close();
          } catch (Exception e) {
            logger.info(e.getStackTrace());
          }
       }
    }
  • 相关阅读:
    js处理json数据,java处理json数据
    sqlmap中##和$$的区别
    tar.gz和bin,以及rpm,deb等linux后缀的文件的区别
    ibatis内置类型
    1099端口被占问题
    动态代理与静态代理的区别
    条款36:绝不重新定义继承而来的non-virtual函数(Never redefine an inherited non-virtual function)
    条款35:考虑virtual函数以外的其他选择(Consider alternative to virtual functions)
    条款34:区分接口继承和实现继承(Different between inheritance of interface and inheritance of implemenation)
    工作好习惯(18之后)
  • 原文地址:https://www.cnblogs.com/eyesmoon/p/7644382.html
Copyright © 2011-2022 走看看