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>
    坚持
  • 相关阅读:
    RK Android7.1 电池电量
    Bat
    RK: 调试 4G模块移远 EC600S-CN
    RK: 调试4G模块 合宙Air720
    关系代数 wiki
    大端与小端的区别
    Microsoft 365 解决方案:如何基于已存在的列表或Excel新建列表
    Microsoft 365 新功能速递:Teams的会议记录将支持对内外部用户共享等新用户体验
    Microsoft 365 解决方案:Office 365 ATP 使用户的收件箱免受钓鱼攻击
    O365事件ID MO222965 -无法访问 Microsoft 365服务
  • 原文地址:https://www.cnblogs.com/gaoSJ/p/13037239.html
Copyright © 2011-2022 走看看