springmvc文件上传

1.添加jar包

 

 2.网页

表单必须是post提交,编码必须是multipart/form-data,文件上传的文本框必须取名

3.在springmvc中配置文件上传解析器

 

 

<!-- 配置文件上传解析器 -->
        
        <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 设置文件上传的大小,单位是字节 -->
        <property name="maxUploadSize" value="20971520"></property>
        </bean>

4.控制层处理代码

 

    @RequestMapping("upload")
    public String upload(MultipartFile myFile,HttpServletRequest request) {
        //1.获取文件上传的保存路径
        String path = request.getServletContext().getRealPath("/update");
        System.out.println(path);
        //2.创建文件对象
        File file=new File(path);
        if(!file.exists()) {
            file.mkdirs();
        }
        
        //3.获取文件名
        String name=System.currentTimeMillis()+myFile.getOriginalFilename();
        File targetFile=new File(path+"/"+name);
        
        //4.把文件写在指定的目录下
        try {
            FileUtils.writeByteArrayToFile(targetFile, myFile.getBytes());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return "redirect:ajax.jsp";
    }

 

posted @ 2019-09-04 23:16  笙无望  阅读(142)  评论(0编辑  收藏  举报