java文件上传(单文件 多文件)与删除
话不多说,请看代码
/** *文件上传--单文件 * *@paramrequest *@paramresponse *@parampath *文件存放路径(path为WebApp\后面的内容) *@return */ publicfinalstaticStringfileUpload(HttpServletRequestrequest, HttpServletResponseresponse,Stringpath){ MultipartHttpServletRequestmultipartRequest=(MultipartHttpServletRequest)request; Map<String,MultipartFile>fileMap=multipartRequest.getFileMap(); MultipartFilemFile=null; for(Iterator<?>i=fileMap.keySet().iterator();i.hasNext();){ Objectobj=i.next(); mFile=(MultipartFile)fileMap.get(obj); } StringfilePath=""; SimpleDateFormatsdf=newSimpleDateFormat("yyyyMMddHHmmssSSS"); try{ //得到上传的文件的文件名 Stringfilename=mFile.getOriginalFilename(); //获取文件后缀名 if(filename!=null&&!("").equals(filename)){ StringfileExt=filename.substring(filename.lastIndexOf(".")); //按时间格式重新生成文件名 StringnewFileName=sdf.format(newDate()) +(int)(Math.random()*100)+fileExt; filePath=path+"/"+newFileName; //得到上传服务器的物理路径 path=request.getSession().getServletContext() .getRealPath("\\"+path); //文件流写到服务器端 FilesaveFile=newFile(path,newFileName); FileCopyUtils.copy(mFile.getBytes(),saveFile); } }catch(IOExceptione){ //TODOAuto-generatedcatchblock e.printStackTrace(); } returnfilePath; } /** *文件上传--多文件 * *@paramrequest *@paramresponse *@paramfilePaths *(fileinputId,WebApp\后面的内容) *@return */ publicfinalstaticMap<String,Object>fileUploads( HttpServletRequestrequest,HttpServletResponseresponse, Stringpath){ MultipartHttpServletRequestmultipartRequest=(MultipartHttpServletRequest)request; Map<String,MultipartFile>fileMap=multipartRequest.getFileMap(); Map<String,Object>filePaths=newHashMap<String,Object>(); //得到上传服务器的物理路径 StringfileUrl=request.getSession().getServletContext() .getRealPath("\\"+path); for(Iterator<?>i=fileMap.keySet().iterator();i.hasNext();){ Objectobj=i.next(); MultipartFilemFile=(MultipartFile)fileMap.get(obj); //得到上传的文件的文件名 Stringfilename=mFile.getOriginalFilename(); if(filename==""||filename==null){ continue; } SimpleDateFormatsdf=newSimpleDateFormat("yyyyMMddHHmmssSSS"); //获取文件后缀名 StringfileExt=filename.substring(filename.lastIndexOf(".")); //按时间格式重新生成文件名 StringnewFileName=sdf.format(newDate()) +(int)(Math.random()*100)+fileExt; StringfilePath=path+"/"+newFileName; //文件流写到服务器端 try{ filePaths.put(obj.toString(),filePath); FilesaveFile=newFile(fileUrl,newFileName); FileCopyUtils.copy(mFile.getBytes(),saveFile); }catch(IOExceptione){ //TODOAuto-generatedcatchblock e.printStackTrace(); } } returnfilePaths; } /** *删除文件, * *@paramrequest请求 *@paramfilePath文件路径 *(static/upload/...) *@return */ publicstaticbooleanfileDelete(HttpServletRequestrequest,StringfilePath){ StringfileUrl=request.getSession().getServletContext() .getRealPath("\\"+filePath);//得到上传服务器的物理路径 Filefile=newFile(fileUrl); fileDelete(file); returnfalse; }
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持毛票票!