SSM文件批量上传

 首先我们需要在SSM框架的配置文件中,配置一个批量上传的组件bean

 <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">    
     <property name="defaultEncoding" value="utf-8"></property>   
      <!-- 配置文件的最大上传容量限制 --> 
     <property name="maxUploadSize" value="50242440"></property>    
    </bean>

其次编写一个简单的jsp页面来进行文件上传操作

<input type="file"  multiple="multiple" name="files" width="120px" >

 multiple="multiple" 属性是配置可以选择多个文件,否则只能选择单个文件

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>文件上传下载</title>
</head>
<body>
    <form action="${pageContext.request.contextPath }/file/upload.html"
        method="post" enctype="multipart/form-data">
        选择文件:<input type="file"  multiple="multiple" name="files" width="120px" > <input
            type="submit" value="上传">
    </form>
</body>
</html>

接下来我们需要编写一个Controller类来实现文件的批量上传

/***
	 * 文件的批量上传
	 * @param files
	 * @param request
	 * @return
	 * @throws Exception
	 * @throws IOException
	 */
	@RequestMapping(value="/file/upload.html",method=RequestMethod.POST)
	public String upload(@RequestParam("files") MultipartFile[] files,MultipartHttpServletRequest request) throws Exception, IOException{
    	//获取文件夹的名字
		List<String[]> filess=new ArrayList<String[]>();
    	String path = request.getSession().getServletContext().getRealPath("/upload");
    	StringBuffer stringbuffer=new StringBuffer();
    	//对传进来的文件数组,进行 循环复制
    	for(MultipartFile multipartFile:files){
    		 //判断文件是否为空
    		if(!multipartFile.isEmpty()) {
    			  //将多个文件名拼接在一个字符串中,用;分隔
    			  stringbuffer.append(multipartFile.getOriginalFilename());	
                  stringbuffer.append(";");
    			  File dir=new File(path, multipartFile.getOriginalFilename());
    			  //将文件名和对应的路径存放在数组中
    			  String[] files1={multipartFile.getOriginalFilename(),dir.toPath().toString()};
    			  //将一个文件的标识信息存入集合中
    			  filess.add(files1);
    			  //System.out.println(dir.toPath());
    			  //文件不存则在创建
    			  if(!dir.exists()&&!dir.isDirectory()){  
    		            dir.mkdirs();  
    		        } 
    			  //文件进行复制
                  multipartFile.transferTo(dir);
    		  }
    	}
          String s=stringbuffer.substring(0, stringbuffer.length()-1);
          //将文件信息集合存入数据库中
          fileOperateService.insertfiles(filess);
          //跳转到调用文件显示的界面
          return "redirect:/file/showall.html";  
     } 

以上便为实现文件批量上传的全部代码,如果不需要存入数据库,然后查询出来的显示到前台,可以将其中部分代码删除

猜你喜欢

转载自blog.csdn.net/weixin_42324471/article/details/82258458