springMVC的简单文件上传

1.导入文件上传所需jar包
- commons-fileupload-1.2.2.jar
- commons-io-2.4.jar

2.配置多部件解析器 — springMVC.xml

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <!-- 上传文件最大限制(单位kb) -->
    <property name="maxUploadSize" value="104857600"/>
</bean>

3.表单修改

<form action="${pageContext.request.contextPath}/file/upload" method="post" enctype="multipart/form-data">
    <input type="file" name="myFile"/>
</form>

4.Controller编写

@Controller
@RequestMapping("/file")
public class FileController{
    @RequestMapping("/upload")
    public void upload(MultipartFile myFile){
        if(myFile != null && myFile.getSize()>0){
            // 获取文件名
            String fileName = myFile.getOriginalFileName();
            File file = new File("F:\\upload\\"+fileName);
            myFile.transferTo(file);
            System.out.println("生成的文件名:"+file.getName());
        }
    }
}

你可能感兴趣的:(spring,mvc,文件上传)