SpringMVC之文件上传

springmvc-servlet.xml

添加以下代码

<!-- 上传文件bean 200*1024*1024 即200M resolveLazily属性为了推迟文件解析, 以便捕获文件大小异常 -->
<bean id="multipartResolver" class= "org.springframework.web.multipart.commons.CommonsMultipartResolver">

    <!-- 限制文件大小 -->
    <property name="maxUploadSize" value="209715200" />
    <property name="defaultEncoding" value="UTF-8" />
    <property name="resolveLazily" value="true" />  
</bean>

upload.jsp

<h3>文件上传</h3>
<form action="<%=request.getContextPath()%>/file/save" method="post" enctype="multipart/form-data">
    <input type="file" name="file" />
    <input type="submit" />
</form>

FileController.java

@Controller
@RequestMapping("/file")
public class FileController {
    @RequestMapping(value="/upload", method=RequestMethod.POST)
    public String saveFile() {
        return "upload";
    }
    @RequestMapping(value="/save", method=RequestMethod.POST)
    public String save(MultipartFile file) throws IOException {
        if (!file.isEmpty()) {
             FileUtils.copyInputStreamToFile(file.getInputStream(), 
                     new File("C:\\Users\\Lee\\Desktop\\" + System.currentTimeMillis() + file.getOriginalFilename()));
             return "success";
        }
        return "fail";
    }
}

使用maven的jetty插件

<plugin>
    <groupId>org.eclipse.jetty</groupId>
    <artifactId>jetty-maven-plugin</artifactId>
    <version>9.2.2.v20140723</version>
 </plugin>

浏览器地址:localhost:8080/file/upload
上传文件
桌面查看

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