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>
    坚持
  • 相关阅读:
    C# post请求,Json转换实体类
    jq div 托拉拽
    json转换成实体类
    C# 队列、锁、异步
    关于C#调用protobuf 序列化和反序列化
    关于System.Data.Entity.Infrastructure.DbUpdateException 的问题
    C# 本地CSS和JS引用无问题,部署服务器之后出现500错误
    windows服务
    下拉加载更多DEMO(js实现)
    禁用iPhone手机浏览器上给电话号码自动加上的link样式
  • 原文地址:https://www.cnblogs.com/gaoSJ/p/13037239.html
Copyright © 2011-2022 走看看