Spring框架实现文件上传功能
在Java中实现文件的上传有多种方式,如smartUpload或是使用Strus2,本文与大家分享使用Spring框架中的MultipartFile类来实例文件的上传。
不啰嗦了,直接上干货。先是编写了一个实现文件上传的类FileUploadingUtil,此类中定义了两个对外公开的方法,upload和getFileMap。
前者需要传入一个Map参数,是用户提交的表单中的文件列表,最终返回值的也是一个Map类型对象,其键名为上传的文件名称,键值为文件在服务器上的存储路径;后者主要是用于测试用途,非主要功能,看官可以忽略此方法。
packagecom.emerson.cwms.utils;
importjava.io.File;
importjava.io.FileInputStream;
importjava.io.FileNotFoundException;
importjava.io.FileOutputStream;
importjava.io.IOException;
importjava.io.InputStream;
importjava.io.OutputStream;
importjava.util.Date;
importjava.util.HashMap;
importjava.util.Iterator;
importjava.util.Map;
importjava.util.Map.Entry;
importorg.springframework.web.multipart.MultipartFile;
/**
*文件上传工具类
*
*@authorChrisMao(Zibing)
*
*/
publicclassFileUploadingUtil{
/**
*服务器上的保存路径,在使用到上传功能的Controller中对其进行赋值
*/
publicstaticStringFILEDIR=null;
/**
*上传多个文件,返回文件名称和服务器存储路径列表
*
*@paramfiles
*@return
*@throwsIOException
*/
publicstaticMapupload(Mapfiles)throwsIOException{
Filefile=newFile(FILEDIR);
if(!file.exists()){
file.mkdir();
}
Mapresult=newHashMap();
Iterator>iter=files.entrySet().iterator();
while(iter.hasNext()){
MultipartFileaFile=iter.next().getValue();
if(aFile.getSize()!=0&&!"".equals(aFile.getName())){
result.put(aFile.getOriginalFilename(),uploadFile(aFile));
}
}
returnresult;
}
/**
*上传单个文件,并返回其在服务器中的存储路径
*
*@paramaFile
*@return
*@throwsFileNotFoundException
*@throwsIOException
*/
privatestaticStringuploadFile(MultipartFileaFile)throwsIOException{
StringfilePath=initFilePath(aFile.getOriginalFilename());
try{
write(aFile.getInputStream(),newFileOutputStream(filePath));
}catch(FileNotFoundExceptione){
logger.error("上传的文件:"+aFile.getName()+"不存在!!");
e.printStackTrace();
}
returnfilePath;
}
/**
*写入数据
*
*@paramin
*@paramout
*@throwsIOException
*/
privatestaticvoidwrite(InputStreamin,OutputStreamout)throwsIOException{
try{
byte[]buffer=newbyte[1024];
intbytesRead=-1;
while((bytesRead=in.read(buffer))!=-1){
out.write(buffer,0,bytesRead);
}
out.flush();
}finally{
try{
in.close();
out.close();
}catch(IOExceptionex){
}
}
}
/**
*遍历服务器目录,列举出目录中的所有文件(含子目录)
*@return
*/
publicstaticMapgetFileMap(){
logger.info(FileUploadingUtil.FILEDIR);
Mapmap=newHashMap();
File[]files=newFile(FileUploadingUtil.FILEDIR).listFiles();
if(files!=null){
for(Filefile:files){
if(file.isDirectory()){
File[]files2=file.listFiles();
if(files2!=null){
for(Filefile2:files2){
Stringname=file2.getName();
logger.info(file2.getParentFile().getAbsolutePath());
logger.info(file2.getAbsolutePath());
map.put(file2.getParentFile().getName()+"/"+name,
name.substring(name.lastIndexOf("_")+1));
}
}
}
}
}
returnmap;
}
/**
*返回文件存储路径,为防止重名文件被覆盖,在文件名称中增加了随机数
*@paramname
*@return
*/
privatestaticStringinitFilePath(Stringname){
Stringdir=getFileDir(name)+"";
Filefile=newFile(FILEDIR+dir);
if(!file.exists()){
file.mkdir();
}
Longnum=newDate().getTime();
Doubled=Math.random()*num;
return(file.getPath()+"/"+num+d.longValue()+"_"+name).replaceAll("","-");
}
/**
*
*@paramname
*@return
*/
privatestaticintgetFileDir(Stringname){
returnname.hashCode()&0xf;
}
}
Controller代码,使用上述定义的FileUploadingUtil类实现文件上传之功能。
packagecom.emerson.cwms.web;
importjava.io.IOException;
importjava.util.Iterator;
importjava.util.Map;
importjava.util.Map.Entry;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
importorg.springframework.stereotype.Controller;
importorg.springframework.ui.Model;
importorg.springframework.web.bind.annotation.RequestMapping;
importorg.springframework.web.bind.annotation.RequestMethod;
importorg.springframework.web.multipart.MultipartHttpServletRequest;
importcom.emerson.cwms.utils.FileUploadingUtil;
/**
*文件上传控制器
*
*@authorChrisMao(Zibing)
*
*/
@Controller
@RequestMapping(value="/files")
publicclassFileController{
@RequestMapping(value="/",method=RequestMethod.GET)
publicStringlist(HttpServletRequestrequest,HttpServletResponseresponse,Modelmodel){
iniFileDir(request);
System.out.println(request.getAttribute("files"));
model.addAttribute("files",FileUploadingUtil.getFileMap());
return"files/list";
}
@RequestMapping(value="/upload",method=RequestMethod.POST)
publicStringdoUpload(HttpServletRequestrequest){
iniFileDir(request);
try{
MultipartHttpServletRequestmRequest=(MultipartHttpServletRequest)request;
MapuploadedFiles=FileUploadingUtil.upload(mRequest.getFileMap());
Iterator>iter=uploadedFiles.entrySet().iterator();
while(iter.hasNext()){
Entryeach=iter.next();
System.out.print("UploadedFileName="+each.getKey());
System.out.println(",SavedPathinServer="+each.getValue());
}
}catch(Exceptione){
e.printStackTrace();
}
return"redirect:/files/";
}
privatevoidiniFileDir(HttpServletRequestrequest){
FileUploadingUtil.FILEDIR=request.getSession().getServletContext().getRealPath("/")+"files/";
if(FileUploadingUtil.FILEDIR==null){
FileUploadingUtil.FILEDIR=request.getSession().getServletContext().getRealPath("/")+"files/";
}
}
}
注意事项:一定要在pom.xml文件中添加对commons-fileupload的依赖引用,否则代码在运行时会提示找不到FileItemFactory类的错误。
依赖引用如下。
commons-fileupload commons-fileupload 1.3.1
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。