.form文件_SSM框架文件上传篇
SSM框架文件上传篇
在Servlet学习阶段,文件上传的代码过于复杂和麻烦,SpringMVC中 对于文件上传显而变的简单易懂,下面我就带这大家配置一下
第一步:引入文件上传需要的jar包 commons-fileupload-1.3.1.jar 和commons-io-2.4 (两种jar包配使用) 放入WEB-INF/lib文件夹下
第二步:需要在springmvc配置文件中配置文件视图解析器的bean节点
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="102400000"></property>
</bean>
第三步:需要在<form>表单中加入文件域<input type=”file”>
第四步:再在<form> 标签加入enctype=” multipart/form-data”>
<form action="mvc/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file"><br>
<input type="submit" value="submit">
</form>
第五步:编写控制层方法
public String upload(HttpServletRequest req) throws Exception{
//转换成多部分request对象
MultipartHttpServletRequest mreq = (MultipartHttpServletRequest)req;
//获得文件对象
MultipartFile file = mreq.getFile("file");
//获得上传文件名
String fileName = file.getOriginalFilename();
//格式化数据
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
//以流的形式写入文件
FileOutputStream fos = new FileOutputStream(req.getSession().getServletContext().getRealPath("/")+
"upload/"+sdf.format(new Date())+fileName.substring(fileName.lastIndexOf('.')));
fos.write(file.getBytes());
fos.flush();
fos.close();
return "hello";
}