结合后台框架springmvc实现文件的简单上传,主要有下面几步:
1. 在前台网页编写最简单的上传组件:(注意enctype=”multipart/form-data”一定要有)
<form name="userForm" action="/springMVC7/file/upload2" method="post" enctype="multipart/form-data" >
选择文件:<input type="file" name="file">
<input type="submit" value="上传" >
</form>
2.在SpringMVC-servlet.xml文件中添加下面的代码:
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="utf-8" />
<property name="maxUploadSize" value="10485760000" />
<property name="maxInMemorySize" value="40960" />
</bean>
3.后台关键代码:
@Controller
@RequestMapping("/file")
public class UploadController {
@RequestMapping("/upload")
public String addUser(@RequestParam("file") CommonsMultipartFile file,HttpServletRequest request) throws IOException{
System.out.println("fileName---->" + file.getOriginalFilename());
if(!file.isEmpty()){
try {
FileOutputStream os = new FileOutputStream("D:/" + new Date().getTime() + file.getOriginalFilename());
InputStream in = file.getInputStream();
int b = 0;
while((b=in.read()) != -1){
os.write(b);
}
os.flush();
os.close();
in.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return "/success";
}