jsp:
<form action="<%=basePath%>upload" method="post" enctype="multipart/form-data">
<input type="file" name="fileName" id="fileName" value=""/>
<input type="submit" value="提交"/>
</form>
conrtoller:
@RequestMapping(value="/upload",method=RequestMethod.POST)
public String uploadFile(@RequestParam("fileName") MultipartFile fileName,Model model,HttpServletRequest request){
String savePath = request.getRealPath("/") + "upload";
InputStream in=null;
File file=null;
FileOutputStream out=null;
try {
in = fileName.getInputStream();
file =new File(savePath,"Austin_"+fileName.getOriginalFilename());
out=new FileOutputStream(file);
byte buffer[] = new byte[1024];
int len = 0;
while ((len = in.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
out.flush();
in.close();
out.close();
model.addAttribute("msg", "上传文件成功");
} catch (IOException e) {
logger.error("上传文件出现异常!");
}
return "index";
}
xml:
<!-- 上传文件 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- one of the properties available; the maximum file size in bytes -->
<property name="defaultEncoding" value="utf-8" />
<property name="maxUploadSize" value="10240000" />
<property name="resolveLazily" value="true"/>
</bean>
<!-- 渲染器 -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/" />
<property name="suffix" value=".jsp" />
</bean>