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();
            }
        }
  • 相关阅读:
    PHP设计模式
    PHP设计模式
    PHP 23种设计模式
    MySQL 中的共享锁和排他锁的用法
    PHP_MySQL高并发加锁事务处理
    Connection: close和Connection: keep-alive有什么区别
    罗辑思维首席架构师:Go微服务改造实践
    真诚与尊重是技术团队的管理要点
    10种常见的软件架构模式
    百亿级微信红包的高并发资金交易系统设计方案
  • 原文地址:https://www.cnblogs.com/peaces/p/14263918.html
Copyright © 2011-2022 走看看