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

    一、SpringMVC的配置文件

      在其中加上

      id属性一定要写上,且只能为multipartResolver

    <!-- 文件上传 -->
        <bean  id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
            <property name="defaultEncoding" value="utf8"></property>
            <property name="maxUploadSize" value="71680"></property>
        </bean>

    二、jsp

      

    enctype属性记得一定要改,method的方式为post
    <form action="${pageContext.request.contextPath}/testUp" method="post" enctype="multipart/form-data">
        文件:<input type="file" name="photo"><br>
        des:<input type="text" name="des"><br>
        <input type="submit"><br>
    
    </form>

    三、写controller层

      

    @Controller
    public class Upfile {
        @RequestMapping("/testUp")
        public void testUp(
              @RequestParam(value = "photo") CommonsMultipartFile file,    @RequestParam(value = "des") String des,
             HttpServletRequest request
                    ) throws IOException { System.out.println(des); // 获取web ServletContext context = request.getServletContext(); // 获取路径的真实路径 String realPath = context.getRealPath("/upload"); // 路径如果不存在就创建路径,这里只是文件夹 File file1 = new File(realPath); if (!file1.exists()) { file1.mkdirs(); } // 获取文件名 String fileName = file.getOriginalFilename(); // 获取输入流 InputStream in = file.getInputStream(); // 获取一个UUID作为前缀 String prefix = UUID.randomUUID().toString().replace("-", ""); // 获取输出流 文件为 路径+前缀+文件名 OutputStream out = new FileOutputStream(new File(realPath + "\" + prefix + fileName)); IOUtils.copy(in, out); out.close(); in.close(); } }
  • 相关阅读:
    RAID卡是否有(启用)缓存对“随机读写”性能有巨大的影响。
    《C++程序设计实践与技巧:测试驱动开发》 环境搭建遇到的坑
    c++ 实现 cout 示例
    c++ 文件
    js 鼠标事件模拟
    eclipse c++ 配置 c++ 17
    c++ 17 vector中string的性能问题 std::vector<std::string> string vs string_view
    c++ 17 模板
    C++17剖析:string在Modern C++中的实现
    编译程序加不加 -lpthread 的区别
  • 原文地址:https://www.cnblogs.com/xuesheng/p/7441181.html
Copyright © 2011-2022 走看看