java之spring mvc之文件上传


目录结构如下:

注意,下面说的配置文件,一般都是值的src下的配置文件,即mvc.xml。如果是web.xml,则直接说 web.xml

1. 文件上传的注意点

表单必须是post提交,必须将 enctype 设置为 “multipart/form-data”,

使用 commons-fileupload 提交文件,需要添加 commons-fileupload 和 commons-io 的 jar 包。

2.Jsp 页面

post" enctype="multipart/form-data"> 文件:

3.Controller类

@Controller
//窄化 
@RequestMapping("/file")
public class UploadController {
    @RequestMapping("/upload.do")
    public String upload(@RequestParam("file")CommonsMultipartFile file,HttpServletRequest req) throws Exception{
        String path=req.getServletContext().getRealPath("/upload");
        //获取文件名
        String fileName=file.getOriginalFilename();
        InputStream is = file.getInputStream();
        OutputStream os = new FileOutputStream(new File(path,fileName));
        byte[] buffer = new byte[400];
        int len=0;
        while((len=is.read(buffer))!=-1){
            os.write(buffer, 0, len);
        }
        os.close();
        is.close();
        return "redirect:/index.jsp";
    }
}

4. 在配置 文件中添加 multipartResolver


    class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        
    

 附录:

附一,这里附上mvc.xml的文件内容

<?xml version="1.0" encoding="UTF-8"?>

    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">
    
    class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/> 
    
    class="org.springframework.web.servlet.view.UrlBasedViewResolver">
        
           
        
        
        
    
    
    class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        
    
    
    package="cn.sxt.controller"/>

 这里再附上 WebContent/WEB-INF/ 下的 web.xml 文件内容

<?xml version="1.0" encoding="UTF-8"?>

  01springmvc_helloworld
  
      springmvc
      class>org.springframework.web.servlet.DispatcherServletclass>
      
      
          contextConfigLocation
          classpath:mvc.xml
      
  
  
      springmvc
      *.do
  
  
    index.html
    index.htm
    index.jsp
    default.html
    default.htm
    default.jsp
  

相关