1.加JAR包
commons-fileupload-1.3.1.jar
commons-io-1.3.2.jar
commons-lang-2.6.jar
commons-logging-1.1.3.jar
2.配置spring.xml文件中的上传信息
<!-- 上传下载 -->
<bean name="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="102400000"></property>
</bean>
3.编写上传代码
@RequestMapping(value="/upload",method=RequestMethod.POST)
public String upload(HttpServletRequest req) throws Exception{
MultipartHttpServletRequest mreq = (MultipartHttpServletRequest)req;
MultipartFile file = mreq.getFile("file");//接收页面上传的文件名字,得到文件
String fileName = file.getOriginalFilename();//上传的文件名
System.out.println(fileName);
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 "index";
}
<!--服务器的根目录在:req.getSession().getServletContext().getRealPath("/") -->
<!--取出上传文件名的后缀:fileName.substring(fileName.lastIndexOf('.')) -->
<!--格式化字符串输出:sdf.format(new Date()) -->
4.编写上传页面……
<form action="userinfo/upload.do" method="post" enctype="multipart/form-data">
<input type="file" name="file"><br>
<input type="submit" value="submit">
</form>