zoukankan      html  css  js  c++  java
  • Java Web 学习(8) —— Spring MVC 之文件上传与下载

    Spring MVC 之文件上传与下载

    上传文件

    表单

    <form action="upload" enctype="multipart/form-data" method="post">
    <input type="file" name="files" multiple/> 
    <input type="submit" value="Upload" />
    </form>
    

    表单的编码类型为multipart/form-data,表单中必须包含类型为file的元素,它会显示成一个按钮,点击时,打开一个对话框,用来选择文件。
    如果上传多个文件,可添加multiple属性。

    上传的文件会被包在一个MultipartFile对象中。

    public interface MultipartFile extends InputStreamSource {
        String getName();
    
        @Nullable
        String getOriginalFilename();
    
        @Nullable
        String getContentType();
    
        boolean isEmpty();
    
        long getSize();
    
        byte[] getBytes() throws IOException;
    
        @Override
        InputStream getInputStream() throws IOException;
    
        default Resource getResource() {
            return new MultipartFileResource(this);
        }
    
        void transferTo(File dest) throws IOException, IllegalStateException;
        
        default void transferTo(Path dest) throws IOException, IllegalStateException {
            FileCopyUtils.copy(getInputStream(), Files.newOutputStream(dest));
        }
    
    }
    

    控制器

    @RequestMapping("upload")
    @ResponseBody
    public String uploadFile (MultipartFile[] files, HttpServletRequest request)
        throws IllegalStateException, IOException {
        String path = request.getServletContext().getRealPath("/files");
        for (MultipartFile file : files) {
            String name = file.getOriginalFilename();
            File f = new File(path, name);
            file.transferTo(f);
        }
    
        return "fin";
    }
    

    配置

    <bean id="multipartResolver"
      class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
      <!-- 上传文件最大 10MB -->
      <property name="maxUploadSize"> 
        <value>10485760</value> 
      </property> 
    </bean>
    

    依赖:commons-fileupload

    下载文件

    @RequestMapping("download")
    public void downloadFile (@RequestParam String name, HttpServletRequest request, HttpServletResponse response) 
        throws IOException {
        String path = request.getServletContext().getRealPath("/files");
        File file = new File(path, name);
        Path filepath = file.toPath();
        response.setHeader("Content-Disposition", "attachment; filename=" + file.getName());
        // response.setContentType
        Files.copy(filepath, response.getOutputStream());
    }
    





    参考资料:《Spring MVC 学习指南》 Paul Deck 著

  • 相关阅读:
    checkpoint出现的时间
    快速断开当前数据库的所有连接的方法
    SQLSERVER备份数据库的时候copy only选项的意思
    SQLSERVER备份事务日志的作用
    SQLSERVER使用密码加密备份文件以防止未经授权还原数据库
    Windows Azure终于到来中国了
    SQLSERVER2005的安装目录结构(下)
    SQLSERVER2005的安装目录结构(上)
    给大家分享两款正在使用的reflector插件
    一套内容采集系统 解放编辑人员
  • 原文地址:https://www.cnblogs.com/JL916/p/11908823.html
Copyright © 2011-2022 走看看