jsp:
<form action="${pageContext.request.contextPath}/login/upload" name="myform" id ="myform" method = "post" enctype="multipart/form-data">
<input name="myFile" type="file" />
<input type="submit" value ="上传"/>
</form>
java
@RequestMapping(value = "login/upload", method = RequestMethod.POST)
public String loginUpload(MultipartHttpServletRequest request) {
// 获得第1张图片(根据前台的name名称得到上传的文件)
MultipartFile file = request.getFile("myFile");
if(file.getSize() != 0){
// 获得文件名:
String filename = file.getOriginalFilename();
String timeType = null;
if(null != filename && !filename.equals("")){
String imgtype = filename.substring(filename.lastIndexOf("."));
// 获取路径
String ctxPath ="G:/rudongImage/myfile/";
// 创建文件
File dirPath = new File(ctxPath);
if (!dirPath.exists()) {
dirPath.mkdirs();
}
//以时间为文件名
Date date = new Date();
SimpleDateFormat sdformat = new SimpleDateFormat("yyyyMMddHHmmss");//24小时制
String LgTime = sdformat.format(date);
timeType = LgTime + imgtype;
File uploadFile = new File(ctxPath + timeType);
try {
InputStream is = file.getInputStream();
FileOutputStream fos = new FileOutputStream(uploadFile);
int b = -1;
byte [] buffer = new byte[1024];
while((b = is.read(buffer)) != -1){
fos.write(buffer,0,b);
}
fos.close();
is.close();
//FileCopyUtils.copy(file.getBytes(), uploadFile);
} catch (IOException e) {
e.printStackTrace();
}
}
}
return "redirect:/";
}
配置XML
<!-- 上传 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 设置上传文件的最大尺寸为2MB
<property name="maxUploadSize">
<value>2097152</value>
</property>
-->
</bean>