zoukankan      html  css  js  c++  java
  • SpringMVC学习笔记(六)

    一.SpringMVC文件的上传

        1.1.需要导入两个jar包

       1.2在SpringMVC配置文件中加入

      

    <!-- upload settings -->
    <bean id="multipartResolver"  class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="102400000">
        <property name="defaultEncoding" value="utf-8"> 
    </property>
    </bean>

    注意:bean的id必须有而且必须叫multipartResolver

    1.3方法代码

       

    @RequestMapping(value="/upload",method=RequestMethod.POST)
    public String upload(HttpServletRequest req) throws Exception{
        MultipartHttpServletRequest mreq = (MultipartHttpServletRequest)req;
        MultipartFile file = mreq.getFile("file");
        String fileName = file.getOriginalFilename();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");        
        FileOutputStream fos = new FileOutputStream(req.getSession().getServletContext().getRealPath("/")+
                "upload/"+sdf.format(new Date())+fileName.substring(fileName.lastIndexOf('.')));
        fos.write(file.getBytes());
        fos.flush();
        fos.close();
         
        return "hello";
    }
    

    二. SpringMVC文件的下载.  

       2.1 准备下载源

      在WebContent下新建files目录,放入aaa.txt,作为下载源

      2.2 在index.jsp添加超链接作为下载入口

       

    <a href="testResponseEntity" id="testJson">testResponseEntity</a><br/>

    2.3 在handler SpringMVCTest中添加接口

    @RequestMapping("testResponseEntity")
    public ResponseEntity<byte[]> testResponseEntity(HttpSession session) throws IOException{
        byte[] body = null;
        ServletContext servletContext = session.getServletContext();
        InputStream in = servletContext.getResourceAsStream("/files/aaa.txt");
        body = new byte[in.available()];
        in.read(body);
             
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Disposition", "attachment;filename=aaa.txt");
        HttpStatus statusCode = HttpStatus.OK;
        ResponseEntity<byte[]> response = new ResponseEntity<>(body, headers, statusCode);
        return response;
    }

      

  • 相关阅读:
    skydriver 工具 SDExplorer
    微软出手了:Live Office与Google 文档大PK
    4§7 二次曲面的直纹性
    5§4 二次曲线的直径
    5§5 二次曲线的主直径
    AI第四章 计算智能(1)
    矩阵理论 第五讲 对角化与Jordan标准形
    矩阵理论第 四讲 矩阵的对角化
    5§7 二次曲线方程的化简与分类
    矩阵论 ppt
  • 原文地址:https://www.cnblogs.com/tony-hyn/p/6225710.html
Copyright © 2011-2022 走看看