您的位置:首页 > 编程语言 > Java开发

springmvc中的上传文件

2015-11-09 16:43 471 查看
引用http://haohaoxuexi.iteye.com/blog/1188116

在使用springMVC进行系统实现时,springMVC默认的解析器里面是没有加入对文件上传的解析的,这可以方便我们实现自己的文件上传。但如果你想使用springMVC对文件上传的解析器来处理文件上传的时候就需要在spring的applicationContext里面加上springMVC提供的MultipartResolver的申明。这样之后,客户端每次进行请求的时候,springMVC都会检查request里面是否包含多媒体信息,如果包含了就会使用MultipartResolver进行解析,springMVC会使用一个支持文件处理的MultipartHttpServletRequest来包裹当前的HttpServletRequest,然后使用MultipartHttpServletRequest就可以对文件进行处理了。Spring已经为我们提供了一个MultipartResolver的实现,我们只需要拿来用就可以了,那就是org.springframework.web.multipart.commons.CommsMultipartResolver。因为springMVC的MultipartResolver底层使用的是Commons-fileupload,所以还需要加入对Commons-fileupload.jar的支持。

<html>
<head>
<title>Upload a file please</title>
</head>
<body>
<h1>Please upload a file</h1>
<!--   enctype(编码格式)必须为multipart/form-data  -->
<form method="post" action="/form" enctype="multipart/form-data">
<input type="text" name="name"/>
<input type="file" name="file"/>
<input type="submit"/>
</form>
</body>
</html>


<!--  这里申明的id必须为multipartResolver  -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">

<!-- one of the properties available; the maximum file size in bytes -->
<property name="maxUploadSize" value="100000"/>
</bean>


CommonsMultipartResolver允许设置的属性有:

    defaultEncoding:表示用来解析request请求的默认编码格式,当没有指定的时候根据Servlet规范会使用默认值ISO-8859-1。当request自己指明了它的编码格式的时候就会忽略这里指定的defaultEncoding。

    uploadTempDir:设置上传文件时的临时目录,默认是Servlet容器的临时目录。

    maxUploadSize:设置允许上传的最大文件大小,以字节为单位计算。当设为-1时表示无限制,默认是-1。
    maxInMemorySize:设置在文件上传时允许写到内存中的最大值,以字节为单位计算,默认是10240。

@Controller
public class FileUpoadController {

@RequestMapping(value = "/form", method = RequestMethod.POST)
public String handleFormUpload(@RequestParam("name") String name,
@RequestParam("file") MultipartFile file) {
//MultipartFile是对当前上传的文件的封装,当要同时上传多个文件时,可以给定多个MultipartFile参数
if (!file.isEmpty()) {
byte[] bytes = file.getBytes();
// store the bytes somewhere
//在这里就可以对file进行处理了,可以根据自己的需求把它存到数据库或者服务器的某个文件夹

return "redirect:uploadSuccess";
} else {
return "redirect:uploadFailure";
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: