• 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(); } }
  • 相关阅读:
    QT1 HelloWorld
    SDL2.0 播放YUV
    vim寄存器
    Makefile模板
    apue初学--DIR
    apue初学--平台的判断
    各种推导式
    文件操作
    list tuple dict set
    字符串和编码
  • 原文地址:https://www.cnblogs.com/xuesheng/p/7441181.html
Copyright © 2020-2023  润新知