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();
            }
        }
  • 相关阅读:
    Django----图片验证码接口
    jwt安装配置
    jwt介绍
    课程章节页面
    git使用整理
    时间复杂度和空间复杂度,排序算法
    linux源码安装mysql,shell编程学习,ubuntu
    linux之任务调度,磁盘分区,yum下载
    linux常用命令修改权限查看文档
    linux用户组相关,密码相关,文件操作,和启动级别
  • 原文地址:https://www.cnblogs.com/peaces/p/14263918.html
Copyright © 2011-2022 走看看