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

    1. 文件上传

      关键代码:

         public void save(File cenclosure,Collectfile collectfile) {
            try {
                InputStream inputStream = new FileInputStream(cenclosure);
                collectfile.setCenclosure(inputStream);
                String name = cenclosure.getName();
                collectfile.setCmenclosure(name);
            } catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
            }
            if (Validation.hasErrors()) {
                this.printError(Validation.getErrorsAsString());
                return;
            }
            collectfileService.save(collectfile);
        }

      注意事项:

      1.其中参数 cenclosure 要和前端form表单中的参数名称一致,否则无法上传

      2.将File类型转换成流的形式,数据库中以二进制的形式存储

    2. 文件下载

      关键代码:

    /**
         * 文件下载
         * @param omenclosure  文件名
         * @throws IOException 
         */
        public void downloadLocal(String id){
            try {
                //根据编号查询得到实体类对象
                Collectfile collectfile = (Collectfile) collectfileService.findById(id);
                
                HttpServletResponse response = response();
                
                //获取InputStrem流
                InputStream in = collectfile.getCenclosure();
                response.setContentType("application/x-msdownload");
                response.addHeader("Content-Disposition", "attachment; filename="+new String(collectfile.getCmenclosure().getBytes("gb2312"),"iso-8859-1"));
                OutputStream out =response.getOutputStream();
                byte[] b = new byte[1024];
                int l;
                while((l = in.read(b)) != -1){
                    out.write(b, 0, l);
                }
                in.close();
                out.flush();
                out.close();
                
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
  • 相关阅读:
    庄家试盘的K线形态
    股票基本知识入门提纲
    我与猫
    夜雨不眠时
    快速排序
    由float转std::string的方法
    BugFree + EasyPHP在Windows平台搭建步骤详解
    安装VS2008的时候Windows Mobile 5.0 SDK R2 for pocket pc错误解决方案
    收集WCF文章
    linq to ef(相当于sql中in的用法)查询语句
  • 原文地址:https://www.cnblogs.com/peaces/p/14263918.html
Copyright © 2011-2022 走看看