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(); } }
  • 相关阅读:
    【leetcode】1442. Count Triplets That Can Form Two Arrays of Equal XOR
    【leetcode】1441. Build an Array With Stack Operations
    【leetcode】1437. Check If All 1's Are at Least Length K Places Away
    cxCheckCombobox
    修改现有字段默认值
    2018.01.02 exprottoexcel
    Statusbar OwnerDraw
    dxComponentPrinter记录
    单据暂存操作思路整理
    设置模式9(装饰者,责任链,桥接,访问者)
  • 原文地址:https://www.cnblogs.com/xuesheng/p/7441181.html
Copyright © 2011-2022 走看看