一,单文件上传,页面部分
<form action="singleFilepload" method="post" enctype="multipart/form-data">涉及图片要用post提交,要设置enctype="multipart/form-data"
选择上传的文件:<input type="file" name = "myfile" ><br>
<input type="submit"value="上传">
</form>
控制器部分
注解@RequestMapping("singleFilepload")
方法public String func1(@RequestBody MultipartFile(或者用CommonsMultipartFile这个类) myfile传入的nama,HttpSession session用来取路径,Model model保存一些值 ){
String path = session.getServletContext().getRealPath("") +"/upload";取到的路径
File destFile = new File(path,myfile.getOriginalFilename());新建文件
if(!destFile.exists()){
destFile.mkdirs();
}
try {
myfile.transferTo(destFile);//转存到destFile
} catch (IllegalStateException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
model.addAttribute("uploadFile",destFile.getAbsolutePath());
return "success";//返回success的jsp页面
}
需要在mvc的配置文件中加文件上传的配置
<!-- 文件上传 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 设置上传文件总大小限制 -->
<property name="maxUploadSize" value="10000000"></property>
</bean>
二,多文件上传
String path = request.getServletContext().getRealPath("") +"/upload";
//文件解析器
CommonsMultipartResolver resolver = new CommonsMultipartResolver(request.getServletContext());
//如果是文件
if(resolver.isMultipart(request)){
MultipartHttpServletRequest mtp = (MultipartHttpServletRequest)request;
Iterator <String> iterator = mtp.getFileNames();
while(iterator.hasNext()){
MultipartFile multipart = mtp.getFile(iterator.next());
saveFIle(f.path);
}
model.addAttribute("uploadFile",path);
return "success";
网友评论