Spring MVC MultipartFile实现图片上传

<!--Spring MVC xml 中配置 -->
<!-- defaultEncoding 默认编码;maxUploadSize 限制大小-->
<!--
配置MultipartResolver 用于文件上传 使用spring的CommosMultipartResolver --> <beans:bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" p:defaultEncoding="UTF-8"   p:maxUploadSize="100000000" > </beans:bean>

2.HTML 或 JSP 页面中添加上传按钮

<form action="fileUpload.do" method="post" enctype="multipart/form-data">  
    选择文件:<input type="file" name="file">  
    <input type="submit" value="提交">   
</form>  

3.Controller

  

public String addContentB(@RequestParam("textFile") MultipartFile textFile,HttpServletRequest request,Model model,Content news){
        String path = request.getSession().getServletContext().getRealPath("upload");//获取路径
        String fileName = textFile.getOriginalFilename();//获取上传文件的名字
        File targetFile = new File(path, fileName); 
        if(!targetFile.exists()){  
            targetFile.mkdirs();//是否存在目录,不存在就创建  
        }  
        //保存  
        try {  
            textFile.transferTo(targetFile); //保存图片
        } catch (Exception e) {  
            e.printStackTrace();  
        } 
    return "sssss";
}

API 地址

https://docs.spring.io/spring/docs/2.0.0/javadoc-api/org/springframework/web/multipart/MultipartFile.html

 

posted @ 2016-01-20 11:04  Crawford  阅读(1105)  评论(1编辑  收藏  举报