`
Java_大猫
  • 浏览: 169869 次
  • 性别: Icon_minigender_1
  • 来自: 大连
社区版块
存档分类
最新评论

commons-fileupload 小结

    博客分类:
  • J2SE
阅读更多
最近写上传文件,用到了这个东西,我想很多人对这个并不陌生。
下面贴出代码。
commons-fileupload 在struts1.x中的应用方法

DynaActionForm uf = (DynaActionForm) form;
		  FormFile file = (FormFile) uf.get("file");
		  
		  System.out.println(file.getFileName());
		  String trackno=request.getParameter("trackno");
		  
		   SimpleDateFormat myFmt=new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss");
		   String fileName= "temp"+myFmt.format(new Date()) +".xls";
		   String realPath ="";
		   realPath = uploadRootPath + File.separator + fileName;
		   FileOutputStream fout = null;
		   fout = new FileOutputStream(realPath);
		   fout.write(file.getFileData());
		   fout.flush();  
		   fout.close(); 

在springMVC中
	Iterator<FileItem> itr = fileItems.iterator();
									
					
					
					
					Map<String, Object> map = new HashMap<String, Object>();
					while (itr.hasNext()) {// 依次处理每个文件
						
						
						FileItem item = (FileItem) itr.next();
						String fileName = item.getName();// 获得文件名,包括路径
						if(!item.isFormField()){
							
						
							
							if (!"".equals(fileName)) {
								
							
								File fullFile = new File(item.getName());
								File savedFile = new File(savePath, fullFile.getName());
								try {
									item.write(savedFile);
								} catch (Exception e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
							
							}
						}else{
							if("title".equals(item.getFieldName())){
								title = new String(item.getString().getBytes("ISO-8859-1"),"UTF-8");
							
							}							
							if("kinds".equals(item.getFieldName())){
								String category1=new String(item.getString().getBytes("ISO-8859-1"),"UTF-8");
							
								categoryList.add(category1);
								
							}
							if("content".equals(item.getFieldName())){
								content=new String(item.getString().getBytes("ISO-8859-1"),"UTF-8");
								
							}
						}
						
					}				
												
			}


如果单独使用的话,如果想获取表单中其他信息 需要判断,才可以

spring上传文件方式:
	Iterator<String> it = multiRequest.getFileNames();
	while(it.hasNext()){
				String key=it.next();
				MultipartFile file = multiRequest.getFile(key);
				String filename=RandomStringUtils.randomNumeric(10)+file.getOriginalFilename();
				
					
					
				//fileUploadHelper.SaveFileFromInputStream(file.getInputStream(), savePath, filename);
				
				 final File targetFile = new File(savePath + File.separator + fileName);
       				 file.transferTo(targetFile);

此处是一个多文件上。单文件都可以

和所有新手一起分享下
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics