zoukankan      html  css  js  c++  java
  • springmvc模式下的上传和下载

    接触了springmvc模式后,对上一次的上传与下载进行优化,

    上次请看这里

    此处上传的功能依旧是采用表格上传。文件格式依旧是

        <form action="${pageContext.request.contextPath}/upload" method="post" enctype="multipart/form-data">

    后台则是

     @RequestMapping("/upload")
        public String upload(MultipartFile file,String userName,HttpServletRequest request) throws IOException {
            String filename = file.getOriginalFilename();
    
            String suffix = filename.substring(filename.lastIndexOf("."));
    
            if(suffix.equalsIgnoreCase(".jpg")){
                String uuid = UUID.randomUUID().toString();
                //FileUtils.copyInputStreamToFile(file.getInputStream(),new File("E://"+uuid+suffix));
    
                file.transferTo(new File("D://"+System.currentTimeMillis()+suffix));//位置存储在硬盘上
    //            file.transferTo(new File(request.getServletContext().getRealPath("/")+"static/userImages/"+file));
    //            存储在项目里的目录下
                request.setAttribute("result","上传成功");
                return "/result.jsp";
            }else{
                request.setAttribute("result","上传失败");
                return "/result.jsp";
            }
        }

    相比之前的传统式上传,springmvc模式下封装了许多繁琐的过程,通过transferTo即可实现一些相应的操作

    而下载也是相应的简化了许多

    @RequestMapping("/download")
        public void download(String filename, HttpServletResponse response, HttpServletRequest request) throws IOException {
            response.setHeader("content-disposition","attachment;filename="+filename);
    
            ServletOutputStream outputStream = response.getOutputStream();
    
            String path = request.getServletContext().getRealPath("images");
    
            File file = new File(path,filename);
    
            byte[] bytes = FileUtils.readFileToByteArray(file);
    
            outputStream.write(bytes);
    
            outputStream.close();
        }

    一般框架会省去许多重复性的工作,但底层的基本原理还是要清楚过程

  • 相关阅读:
    设置IIS允许下载.config文件
    SQL Server 触发器
    MVC参数自动装配
    sql之left join、right join、inner join的区别
    C# 之泛型详解
    Frameset使用教程
    网页引用Font Awesome图标
    ubuntu下apache2 安装 配置 卸载 CGI设置 SSL设置
    深入理解JAVA I/O系列二:字节流详解
    深入理解JAVA I/O系列三:字符流详解
  • 原文地址:https://www.cnblogs.com/lin530/p/11794769.html
Copyright © 2011-2022 走看看