spring mvc上传文件

来源:互联网 发布:引用百度地图js 编辑:程序博客网 时间:2024/06/06 00:47

页面form中提交enctype="multipart/form-data"的数据时,需要springmvcmultipart类型的数据进行解析。


springmvc.xml配置

<!-- 文件上传配置 --><bean id="multipartResolver"  class="org.springframework.web.multipart.commons.CommonsMultipartResolver"><!-- 设置编码格式 -->  <property name="defaultEncoding" value="utf-8"></property> <!-- 设置文件大小 -->          <property name="maxUploadSize" value="10485760000"></property>        <!-- 设置缓冲区大小 -->          <property name="maxInMemorySize" value="40960"></property>  </bean> 

@Controllerpublic class UploadController {//到达上传页面@RequestMapping("/toUpload.do")public String toUpload(){return "forward:upload.jsp";}//文件上传/** * spring mvc封装了上传文件  将其封装为一个file对象 * */@RequestMapping("/upload.do")public String upload(@RequestParam("file") CommonsMultipartFile file,HttpServletRequest req){//获取上传位置String path=req.getRealPath("/upload");//获取文件名String filename=file.getOriginalFilename();try {InputStream is = file.getInputStream();OutputStream os = new FileOutputStream(new File(path,filename));int len=0;byte[] buffer = new byte[400];while((len=is.read(buffer))!=-1){os.write(buffer, 0, len);}os.close();is.close();} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}return "redirect:index.jsp";}@RequestMapping("/batch.do")public String batch(@RequestParam("file") CommonsMultipartFile file[],HttpServletRequest req){//获取上传位置String path=req.getRealPath("/upload");for(int i=0;i<file.length;i++){//获取文件名String filename=file[i].getOriginalFilename();try {InputStream is = file[i].getInputStream();OutputStream os = new FileOutputStream(new File(path,filename));int len=0;byte[] buffer = new byte[400];while((len=is.read(buffer))!=-1){os.write(buffer, 0, len);}os.close();is.close();} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}return "redirect:index.jsp";}}


0 0
原创粉丝点击