• spring mvc 文件上传


    1. spring -mvc.xml配置文件中,配置“multipartResolver”

    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
            <property name="maxUploadSize" value="50000000"/>
            <property name="defaultEncoding" value="UTF-8"/>
    </bean>

    2. 导入包

    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.3.1</version>
    </dependency>
    
    <dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
      <version>2.4</version>
    </dependency>
    
    <dependency>
      <groupId>commons-lang</groupId>
      <artifactId>commons-lang</artifactId>
      <version>2.4</version>
    </dependency>

    3. 前端 html 代码

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

    4. tomcat 配置静态地址

      3.1 进入tomcat 目录,打开 server.xml 

      3.2 在 server.xml 的<Host> 标签对内添加代码
    <!-- 
         docBase:本地路径
         path:虚拟路径
     -->
    <Context docBase="F: omcat-upload" path="/upload" debug="0" reloadable="true"/>

    5. 文件上传工具类

    import org.apache.commons.io.FilenameUtils;
    import org.apache.commons.lang.math.RandomUtils;
    import org.springframework.web.multipart.MultipartFile;
    
    import javax.servlet.http.HttpServletRequest;
    import java.io.File;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    
    public class Upload {
    
        //源文件名
        private String originalFilename;
    
        //源文件后缀名
        private String suffix;
    
        //存入数据库里的tomcat虚拟路径
        private String dbPath;
    
        public void setOriginalFilename(String originalFilename) {
            this.originalFilename = originalFilename;
        }
    
        public void setSuffix(String suffix) {
            this.suffix = suffix;
        }
    
        public void setDbPath(String dbPath) {
            this.dbPath = dbPath;
        }
    
        public String getOriginalFilename() {
            return originalFilename;
        }
    
        public String getSuffix() {
            return suffix;
        }
    
        public String getDbPath() {
            return dbPath;
        }
    
        /**
         * 文件上传工具类
         * @param attach
         * @param request
         * @param uploader 文件上传者
         * @return
         */
        public boolean doUpload(MultipartFile attach, HttpServletRequest request, String uploader){
    
            if(!attach.isEmpty()){
    
                originalFilename = attach.getOriginalFilename();
    System.out.println("==>上传的文件名:"+originalFilename);
    
                suffix = FilenameUtils.getExtension(originalFilename);
    System.out.println("==>上传的文件后缀名:"+suffix);
    
                long fileSize = attach.getSize();
    System.out.println("==>上传文件的大小:"+fileSize);
    
                String currentFilename = System.currentTimeMillis()+ RandomUtils.nextInt(1000000)+"."+suffix;
    System.out.println("==>存储的上传文件名:"+currentFilename);
    
                String savePath = "F:/tomcat-upload"+request.getContextPath() +"/" + uploader + "/" + new SimpleDateFormat("yyyy-MM-dd").format(new Date());
    System.out.println("==>上传文件保存的真实路径:"+savePath);
    
                File targetFile = new File(savePath, currentFilename);
                if(!targetFile.exists()){
                    targetFile.mkdirs();
                }
    
                try{
                    attach.transferTo(targetFile);
                }catch (Exception e){
                    e.printStackTrace();
                    request.setAttribute("uploadMsg","文件上传失败!");
                    return false;
                }
    
                dbPath = "/upload" + request.getContextPath() + "/" + uploader + "/" + new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + "/" + currentFilename;
                return true;
            }else{
                return false;
            }
    
        }
    }

    6. controller 代码

      @RequestMapping(value = "/url")
        public String doEditor(
                @RequestParam(value="file",required=false)MultipartFile file,HttpServletRequest request) {
    
            Upload upload = new Upload();
            boolean flag = upload.doUpload(file,request,uploader);
                
            if (flag) {
                
                return "url";
            } else{
                
                return "url";
            }
            
        }

     controller层只提供主要代码,部分代码需要根据自己实际情况进行添加。

  • 相关阅读:
    作业: 小型购物系统1---按顺序编写
    字典操作学习小结
    字符操作学习笔记小结
    列表,元组等学习笔记小结
    模块及其数据类型小结
    python3学习笔记----基础知识1
    压力山大
    下周一开始上班啦!
    凌晨12点,沉迷学习,无法自拔...
    web前端开发2018年12月找工作总结
  • 原文地址:https://www.cnblogs.com/lcsin/p/11667836.html
Copyright © 2020-2023  润新知