版权声明:本文为博主原创文章,如需转载,请标明出处。 https://blog.csdn.net/alan_liuyue/article/details/79327717
简介
1.上一篇博客我们讲解了普遍情况下都适用的文件上传的功能代码,那么本篇博客将会重点讲解SSH框架之SpringMVC的文件上传代码;
2.SpringMVC框架本身就已经封装了特有的文件获取和解析的方法,所以,我们之需要将这些方法熟练运用展示出即可;
3.本篇实例将会分成四个步骤,给您展示一步到位的完善的springmvc文件上传:
(1).需要的jar包;
(2).jsp页面;
(3).xml配置;
(4).后台controller处理方法;
实例
1.需要提供的jar包:commons.fileupload-1.2.1.jar; commons.io-1.4.0.jar
2.jsp页面:
<form action="uploadId" method="post" enctype="multipart/form-data">
<input type="file" name="idPic" />
<button >Submit</button>
</form>
3.xml文件配置:
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8" />
<property name="maxUploadSize" value="200000"/>
<property name="uploadTempDir" value="uploadTempDirectory" />
</bean>
4.后台controller处理方法类:
/**
* springMVC文件上传方法实例
* @author hqc
*
*/
@Controller
@RequestMapping(value = "${adminPath}/upload")
public class Uploadfile(){
/**
* 单文件上传:
* 用@RequestParam注解来指定表单上的file为MultipartFile
* 参数都会实行自动装配~
* @param multipartfile
* @return
* @throws IOException
*/
@RequestMapping(value = "/uploadId")
@ResponseBody
public String idIdentification(@RequestParam("idPic") MultipartFile multipartfile) throws IOException {
System.out.println("getOriginalFilename:"+multipartfile.getOriginalFilename());
System.out.println("getName:"+multipartfile.getName());
String savePath = request.getSession().getServletContext().getRealPath("/uploadFile/placeImage");
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
String fileName = imageFile.getOriginalFilename();
String lastThreeLetter = fileName.substring(fileName.lastIndexOf("."));
String sqlName = sdf.format(new Date())+(int)(Math.random()*10000)+lastThreeLetter;
File saveFile = new File(savePath+File.separator+sqlName);
multipartfile.transferTo(saveFile);
String json = "{\"result\":\""+result+"\"}";
return json;
}
/**
* 多文件上传:
* 前台可上传多个文件,使用MultipartFile的数组形式接收
* @param multipartfiles
* @return
* @throws IllegalStateException
* @throws IOException
*/
@RequestMapping(value = "/multiUploadId")
public String multiUpload(@RequestParam("idPic") MultipartFile[] multipartfiles)
throws IllegalStateException, IOException {
String savePath = request.getSession().getServletContext().getRealPath("/uploadFile/placeImage");
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
String timePath = sdf.format(new Date());
if(null != multipartfiles && multipartfiles.length > 0){
for(MultipartFile file : multipartfiles){
String fileName = file.getOriginalFilename();
String lastThreeLetter = fileName.substring(fileName.lastIndexOf("."));
String sqlName = timePath+(int)(Math.random()*10000)+lastThreeLetter;
File saveFile = new File(savePath+File.separator+sqlName);
multipartfile.transferTo(saveFile);
}
}
return "redirect:uploadPage";
}
}
总结
1.以上就是springMVC上传文件的全部流程,代码也是简洁方便,对于还不是很了解springmvc上传文件的程序猿还是有帮助的,有需要的可以自行复制代码,然后可以经过自己的进一步加工,形成对自己最有效的一套代码;
2.实践是检验认识真理的唯一标准,代码好不好用,何不亲自动手实践看看;