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

    在web学习中我们用到的是 Apache fileupload这个组件来实现上传,在springmvc中对它进行了封装,让我们使用起来比较方便,但是底层还是由Apache fileupload来实现的。springmvc中由MultipartFile接口来实现文件上传。

    1 导入jar包

    • commons-fileupload
    • commons-io

    2 前端jsp页面

    • input的type设置为file

    • form表单的method设为post,

    • form表单的enctype设置为multipart/form-data,以二进制的形式传输数据。

      <%@ page language="java" contentType="text/html; charset=UTF-8"
          pageEncoding="UTF-8"%>
      <!DOCTYPE html>
      <html>
      <head>
      <meta charset="ISO-8859-1">
      <title>Insert title here</title>
      </head>
      <body>
          <form action="/ssm/file/imgUpload" enctype="multipart/form-data" method="post">
              <input type="file" name="file"><br><br>
              <input type="submit" value="上传">
          </form>
      </body>
      </html>

    3Controller层接收

    @RequestMapping("/upload")
    public String upload(@RequestParam("file") MultipartFile file, HttpServletRequest req)
            throws IllegalStateException, IOException {
    
        // 判断文件是否为空,空则返回失败页面
        if (file.isEmpty()) {
            return "failed";
        }
        // 获取文件存储路径(绝对路径)
        String path = req.getServletContext().getRealPath("/WEB-INF/file");
        // 获取原文件名
        String fileName = file.getOriginalFilename();
        // 创建文件实例
        File filePath = new File(path, fileName);
        // 如果文件目录不存在,创建目录
        if (!filePath.getParentFile().exists()) {
            filePath.getParentFile().mkdirs();
            System.out.println("创建目录" + filePath);
        }
        // 写入文件
        file.transferTo(filePath);
        return "success";
    } 

    4 springmvc.xml配置CommonsMultipartResolver。

    <bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!--上传文件的最大大小,单位为字节 --> 
        <property name="maxUploadSize" value="17367648787"></property>
         
        <!-- 上传文件的编码 -->
        <property name="defaultEncoding" value="UTF-8"></property>
    </bean>
    坚持
  • 相关阅读:
    java三大特性或java对象的三大特性?
    数据结构与算法第10周作业——二叉树的创建和遍历算法
    JDBC的应用
    数据结构与算法--第5周作业(线性表合并算法)
    数据结构与算法--第4周作业(单链表)
    WEB(JSP)下的JDBC操作实验
    application下的JDBC操作
    思考题:JSP的指令inclue和动作include的区别
    css3动画小试
    JS => 函数
  • 原文地址:https://www.cnblogs.com/gaoSJ/p/13037239.html
Copyright © 2011-2022 走看看