zoukankan      html  css  js  c++  java
  • 【JavaWeb】SpringMvc 文件上传

    1. 添加上传文件组件支持

        <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>

    2. Controller部分

    @RequestMapping("upload.do")
        public String upload(@RequestParam("file") MultipartFile file)
                throws IllegalStateException, IOException {
            String basePath = "xxx";
                String path = "";
                if (!file.isEmpty()) {
                    if (file.getOriginalFilename().endsWith("txt"))
                        path = basePath + "doc"; 
                    else if (file.getOriginalFilename().endsWith("jpg") || file.getOriginalFilename().endsWith("gif")
                            || file.getOriginalFilename().endsWith("png"))
                        path = basePath + "img";
                    else
                        path = basePath + "other";
                    String fileName = f.getOriginalFilename();
                    File tarFile = new File(path, fileName);
                    file.transferTo(tarFile);
                }
            return "index.jsp";
        }

    3. html部分

    <form action="upload.do" enctype="multipart/form-data" method="post">
            <input type="file" name="file">
            <input type="submit" value="上传">
        </form>

    4. 多文件上传

    @RequestMapping("upload.do")
        public String upload(@RequestParam("file") MultipartFile[] file, HttpServletRequest req)
                throws IllegalStateException, IOException {
            String basePath = "xxx";
            for (MultipartFile f : file) {
                String path = "";
                if (!f.isEmpty()) {
                    if (f.getOriginalFilename().endsWith("txt"))
                        path = basePath + "doc"; 
                    else if (f.getOriginalFilename().endsWith("jpg") || f.getOriginalFilename().endsWith("gif")
                            || f.getOriginalFilename().endsWith("png"))
                        path = basePath + "img";
                    else
                        path = basePath + "other";
                    String fileName = f.getOriginalFilename();
                    File tarFile = new File(path, fileName);
                    f.transferTo(tarFile);
                }
            }
            return "index.jsp";
  • 相关阅读:
    洛谷 P5057 [CQOI2006]简单题 题解
    洛谷 P3368 【模板】树状数组 2 题解
    洛谷 P3374 【模板】树状数组 1 题解
    洛谷 P2023 [AHOI2009]维护序列 题解
    洛谷 P2253 好一个一中腰鼓! 题解
    求最长不下降/上升/下降/不上升子序列
    [SQL Server]Index/deadlock
    Ubuntu 14.04下从源码安装qt4.x
    Ubuntu系统下Import cv2提示no modules ...错误
    Ubuntu 14.04下安装CUDA8.0
  • 原文地址:https://www.cnblogs.com/cnsec/p/13286760.html
Copyright © 2011-2022 走看看