spring mvc 文件上传

来源:互联网 发布:cf滑步教程 知乎 编辑:程序博客网 时间:2024/06/06 05:00

  spring mvc 文件上传


1.在页面的form表单:

<form name ="form1" action="upload.do" method="post" enctype="multipart/form-data"><input name="file" type="file" id="" style="font-size:12px;"><input name="file" type="file" id="" style="font-size:12px;"><input name="file" type="file" id="" style="font-size:12px;"><input type="submit" name="Submit" value="开始上传"></form>


2.要在spring-mvc.xml 中加入:

            <!-- 上传文件 --><bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"><property name="maxUploadSize" value="500000000000"></property></bean> 

3.在controller中的代码:

@RequestMapping(value="pub/admin/system/enclosure/upload",method=RequestMethod.POST)public String upload(String[] no,String type1,@RequestParam("file")MultipartFile[] files,HttpServletRequest request) {int  i = 0;for(MultipartFile file:files){if(file.isEmpty()) continue;String orginname = file.getOriginalFilename();String path = request.getContextPath();//JavaPlatString basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";//取得根目录路径  String rootPath=getClass().getResource("/").getFile().toString();  ///D:/java工程1/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/JavaPlat/WEB-INF/classes/String temp=rootPath;   // 文件保存路径              String file1Path = request.getSession().getServletContext().getRealPath("/");//D:\java工程1\.metadata\.plugins\org.eclipse.wst.server.core\tmp1\wtpwebapps\JavaPlat\String path2= file1Path+"pub\\admin\\upload\\";if(type1.equals("0")){ /*path2 = "D:/java工程1/JavaPlat/src/main/webapp/pub/admin/upload/picture/";*/ path2 = path2+"picture\\";}else if(type1.equals("1")){/* path2 = "D:\\java工程1\\JavaPlat\\src\\main\\webapp\\pub\\admin\\upload\\flash\\";*/ path2 = path2+"flash\\";}else if(type1.equals("2")){/* path2 = "D:\\java工程1\\JavaPlat\\src\\main\\webapp\\pub\\admin\\upload\\Multimedia\\";*/ path2 = path2+"Multimedia\\";}else{/* path2 ="D:/java工程1/JavaPlat/src/main/webapp/pub/admin/upload/others/";*/ path2 = path2+"others\\";}//上传到服务器的路径//String path2 = path1+"pub\\admin\\upload\\";/*SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式String mma =df1.format(new Date()); path2= path2+mma+"\\";File file1 =new File(path2);//file.mkdir();//创建文件夹if(file1.exists()) {      System.out.println("目录已经!!");  }else{       file1.mkdir();      }*///创建随机文件名UUID uuid1 = UUID.randomUUID();String uuidStr1=uuid1.toString().replace("-", "");  String fileName =file.getOriginalFilename();            // 获取图片的扩展名            String extensionName = fileName                    .substring(fileName.lastIndexOf(".") + 1);                        String wenjianming = uuidStr1                    + "." + extensionName; String filename2=path2+wenjianming; System.out.println(filename2);try {file.transferTo(new File(filename2));} catch (IllegalStateException | IOException e) {e.printStackTrace();}}
4.要加入文件上传和下载的架包:

0 0