• 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 著

  • 相关阅读:
    SQL_Server_2005_字符串函数(描述及实例)
    固定在左右两侧不动的广告条 样式
    jquery 浏览器判断
    sqlserver 2005无限极分类 获取 所有子分类
    asp.net使用treeview控件,递归加载
    C++day15 学习笔记
    Win32编程day02 学习笔记
    Win32编程day04 学习笔记
    C++day16 学习笔记
    Win32编程day05 学习笔记
  • 原文地址:https://www.cnblogs.com/JL916/p/11908823.html
Copyright © 2020-2023  润新知