本文小编为大家详细介绍“Java怎么实现SpringBoot单文件和多文件的上传功能”,内容详细,步骤清晰,细节处理妥当,希望这篇“Java怎么实现SpringBoot单文件和多文件的上传功能”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。

一、公共文件存储代码
1.FileUploadUtils.java

packagecom.springcloud.blog.admin.util.file;/***@description:文件上传工具类*@author:youcong*@time:2020/9/2811:34*/importcom.springcloud.blog.admin.exception.file.FileNameLengthLimitExceededException;importcom.springcloud.blog.admin.exception.file.FileSizeLimitExceededException;importcom.springcloud.blog.admin.exception.file.InvalidExtensionException;importcom.springcloud.blog.admin.util.DateUtils;importcom.springcloud.blog.admin.util.IdUtils;importcom.springcloud.blog.admin.util.StringUtils;importorg.apache.commons.fileupload.FileUploadBase;importorg.apache.commons.io.FilenameUtils;importorg.springframework.web.multipart.MultipartFile;importjava.io.File;importjava.io.IOException;publicclassFileUploadUtils{/***默认大小50M*/publicstaticfinallongDEFAULT_MAX_SIZE=50*1024*1024;/***默认的文件名最大长度100*/publicstaticfinalintDEFAULT_FILE_NAME_LENGTH=100;/***默认上传的地址*/privatestaticStringdefaultBaseDir="D://test//";/***资源映射路径前缀*/publicstaticStringresource_prefix="D://test//";publicstaticvoidsetDefaultBaseDir(StringdefaultBaseDir){FileUploadUtils.defaultBaseDir=defaultBaseDir;}publicstaticStringgetDefaultBaseDir(){returndefaultBaseDir;}/***以默认配置进行文件上传**@paramfile上传的文件*@return文件名称*@throwsException*/publicstaticfinalStringupload(MultipartFilefile)throwsIOException{try{returnupload(getDefaultBaseDir(),file,MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION);}catch(Exceptione){thrownewIOException(e.getMessage(),e);}}/***文件上传**@parambaseDir相对应用的基目录*@paramfile上传的文件*@paramallowedExtension上传文件类型*@return返回上传成功的文件名*@throwsFileSizeLimitExceededException如果超出最大大小*@throwsFileNameLengthLimitExceededException文件名太长*@throwsIOException比如读写文件出错时*@throwsInvalidExtensionException文件校验异常*/publicstaticfinalStringupload(StringbaseDir,MultipartFilefile,String[]allowedExtension)throwsFileUploadBase.FileSizeLimitExceededException,IOException,FileNameLengthLimitExceededException,InvalidExtensionException{intfileNamelength=file.getOriginalFilename().length();if(fileNamelength>FileUploadUtils.DEFAULT_FILE_NAME_LENGTH){thrownewFileNameLengthLimitExceededException(FileUploadUtils.DEFAULT_FILE_NAME_LENGTH);}assertAllowed(file,allowedExtension);StringfileName=extractFilename(file);Filedesc=getAbsoluteFile(baseDir,fileName);file.transferTo(desc);StringpathFileName=getPathFileName(baseDir,fileName);returnpathFileName;}/***编码文件名*/publicstaticfinalStringextractFilename(MultipartFilefile){StringfileName=file.getOriginalFilename();Stringextension=getExtension(file);fileName=DateUtils.datePath()+"/"+IdUtils.fastUUID()+"."+extension;returnfileName;}privatestaticfinalFilegetAbsoluteFile(StringuploadDir,StringfileName)throwsIOException{Filedesc=newFile(uploadDir+File.separator+fileName);if(!desc.getParentFile().exists()){desc.getParentFile().mkdirs();}if(!desc.exists()){desc.createNewFile();}returndesc;}privatestaticfinalStringgetPathFileName(StringuploadDir,StringfileName)throwsIOException{intdirLastIndex=defaultBaseDir.length()+1;StringcurrentDir=StringUtils.substring(uploadDir,dirLastIndex);StringpathFileName=resource_prefix+"/"+currentDir+"/"+fileName;returnpathFileName;}/***文件大小校验**@paramfile上传的文件*@return*@throwsFileSizeLimitExceededException如果超出最大大小*@throwsInvalidExtensionException*/publicstaticfinalvoidassertAllowed(MultipartFilefile,String[]allowedExtension)throwsFileSizeLimitExceededException,InvalidExtensionException{longsize=file.getSize();if(DEFAULT_MAX_SIZE!=-1&&size>DEFAULT_MAX_SIZE){thrownewFileSizeLimitExceededException(DEFAULT_MAX_SIZE/1024/1024);}StringfileName=file.getOriginalFilename();Stringextension=getExtension(file);if(allowedExtension!=null&&!isAllowedExtension(extension,allowedExtension)){if(allowedExtension==MimeTypeUtils.IMAGE_EXTENSION){thrownewInvalidExtensionException.InvalidImageExtensionException(allowedExtension,extension,fileName);}elseif(allowedExtension==MimeTypeUtils.FLASH_EXTENSION){thrownewInvalidExtensionException.InvalidFlashExtensionException(allowedExtension,extension,fileName);}elseif(allowedExtension==MimeTypeUtils.MEDIA_EXTENSION){thrownewInvalidExtensionException.InvalidMediaExtensionException(allowedExtension,extension,fileName);}elseif(allowedExtension==MimeTypeUtils.VIDEO_EXTENSION){thrownewInvalidExtensionException.InvalidVideoExtensionException(allowedExtension,extension,fileName);}else{thrownewInvalidExtensionException(allowedExtension,extension,fileName);}}}/***判断MIME类型是否是允许的MIME类型**@paramextension*@paramallowedExtension*@return*/publicstaticfinalbooleanisAllowedExtension(Stringextension,String[]allowedExtension){for(Stringstr:allowedExtension){if(str.equalsIgnoreCase(extension)){returntrue;}}returnfalse;}/***获取文件名的后缀**@paramfile表单文件*@return后缀名*/publicstaticfinalStringgetExtension(MultipartFilefile){Stringextension=FilenameUtils.getExtension(file.getOriginalFilename());if(StringUtils.isEmpty(extension)){extension=MimeTypeUtils.getExtension(file.getContentType());}returnextension;}}2.FileUtils.java

packagecom.springcloud.blog.admin.util.file;importjavax.servlet.http.HttpServletRequest;importjava.io.*;importjava.net.URLEncoder;/***文件处理工具类**@authoryoucong*/publicclassFileUtilsextendsorg.apache.commons.io.FileUtils{publicstaticStringFILENAME_PATTERN="[a-zA-Z0-9_\-\|\.\u4e00-\u9fa5]+";/***输出指定文件的byte数组**@paramfilePath文件路径*@paramos输出流*@return*/publicstaticvoidwriteBytes(StringfilePath,OutputStreamos)throwsIOException{FileInputStreamfis=null;try{Filefile=newFile(filePath);if(!file.exists()){thrownewFileNotFoundException(filePath);}fis=newFileInputStream(file);byte[]b=newbyte[1024];intlength;while((length=fis.read(b))>0){os.write(b,0,length);}}catch(IOExceptione){throwe;}finally{if(os!=null){try{os.close();}catch(IOExceptione1){e1.printStackTrace();}}if(fis!=null){try{fis.close();}catch(IOExceptione1){e1.printStackTrace();}}}}/***删除文件**@paramfilePath文件*@return*/publicstaticbooleandeleteFile(StringfilePath){booleanflag=false;Filefile=newFile(filePath);//路径为文件且不为空则进行删除if(file.isFile()&&file.exists()){file.delete();flag=true;}returnflag;}/***文件名称验证**@paramfilename文件名称*@returntrue正常false非法*/publicstaticbooleanisValidFilename(Stringfilename){returnfilename.matches(FILENAME_PATTERN);}/***下载文件名重新编码**@paramrequest请求对象*@paramfileName文件名*@return编码后的文件名*/publicstaticStringsetFileDownloadHeader(HttpServletRequestrequest,StringfileName)throwsUnsupportedEncodingException{finalStringagent=request.getHeader("USER-AGENT");Stringfilename=fileName;if(agent.contains("MSIE")){//IE浏览器filename=URLEncoder.encode(filename,"utf-8");filename=filename.replace("+","");}elseif(agent.contains("Firefox")){//火狐浏览器filename=newString(fileName.getBytes(),"ISO8859-1");}elseif(agent.contains("Chrome")){//google浏览器filename=URLEncoder.encode(filename,"utf-8");}else{//其它浏览器filename=URLEncoder.encode(filename,"utf-8");}returnfilename;}}3.MimeTypeUtils.java

packagecom.springcloud.blog.admin.util.file;/***@description:*@author:youcong*@time:2020/9/2811:37*/publicclassMimeTypeUtils{publicstaticfinalStringIMAGE_PNG="image/png";publicstaticfinalStringIMAGE_JPG="image/jpg";publicstaticfinalStringIMAGE_JPEG="image/jpeg";publicstaticfinalStringIMAGE_BMP="image/bmp";publicstaticfinalStringIMAGE_GIF="image/gif";publicstaticfinalString[]IMAGE_EXTENSION={"bmp","gif","jpg","jpeg","png"};publicstaticfinalString[]FLASH_EXTENSION={"swf","flv"};publicstaticfinalString[]MEDIA_EXTENSION={"swf","flv","mp3","wav","wma","wmv","mid","avi","mpg","asf","rm","rmvb"};publicstaticfinalString[]VIDEO_EXTENSION={"mp4","avi","rmvb"};publicstaticfinalString[]DEFAULT_ALLOWED_EXTENSION={//图片"bmp","gif","jpg","jpeg","png",//wordexcelpowerpoint"doc","docx","xls","xlsx","ppt","pptx","html","htm","txt",//压缩文件"rar","zip","gz","bz2",//视频格式"mp4","avi","rmvb",//pdf"pdf"};publicstaticStringgetExtension(Stringprefix){switch(prefix){caseIMAGE_PNG:return"png";caseIMAGE_JPG:return"jpg";caseIMAGE_JPEG:return"jpeg";caseIMAGE_BMP:return"bmp";caseIMAGE_GIF:return"gif";default:return"";}}}4.FileException.java

packagecom.springcloud.blog.admin.exception.file;importcom.springcloud.blog.admin.exception.BaseException;/***@description:文件信息异常类*@author:youcong*@time:2020/9/2811:41*/publicclassFileExceptionextendsBaseException{privatestaticfinallongserialVersionUID=1L;publicFileException(Stringcode,Object[]args){super("file",code,args,null);}}5.FileNameLengthLimitExceededException.java

packagecom.springcloud.blog.admin.exception.file;/***@description:文件名称超长限制异常类*@author:youcong*@time:2020/9/2811:41*/publicclassFileNameLengthLimitExceededExceptionextendsFileException{privatestaticfinallongserialVersionUID=1L;publicFileNameLengthLimitExceededException(intdefaultFileNameLength){super("upload.filename.exceed.length",newObject[]{defaultFileNameLength});}}6.FileSizeLimitExceededException.java

packagecom.springcloud.blog.admin.exception.file;/***@description:文件名大小限制异常类*@author:youcong*@time:2020/9/2811:42*/publicclassFileSizeLimitExceededExceptionextendsFileException{privatestaticfinallongserialVersionUID=1L;publicFileSizeLimitExceededException(longdefaultMaxSize){super("upload.exceed.maxSize",newObject[]{defaultMaxSize});}}7.InvalidExtensionException.java

packagecom.springcloud.blog.admin.exception.file;/***@description:文件上传错误异常类*@author:youcong*@time:2020/9/2811:42*/importorg.apache.commons.fileupload.FileUploadException;importjava.util.Arrays;publicclassInvalidExtensionExceptionextendsFileUploadException{privatestaticfinallongserialVersionUID=1L;privateString[]allowedExtension;privateStringextension;privateStringfilename;publicInvalidExtensionException(String[]allowedExtension,Stringextension,Stringfilename){super("filename:["+filename+"],extension:["+extension+"],allowedextension:["+Arrays.toString(allowedExtension)+"]");this.allowedExtension=allowedExtension;this.extension=extension;this.filename=filename;}publicString[]getAllowedExtension(){returnallowedExtension;}publicStringgetExtension(){returnextension;}publicStringgetFilename(){returnfilename;}publicstaticclassInvalidImageExtensionExceptionextendsInvalidExtensionException{privatestaticfinallongserialVersionUID=1L;publicInvalidImageExtensionException(String[]allowedExtension,Stringextension,Stringfilename){super(allowedExtension,extension,filename);}}publicstaticclassInvalidFlashExtensionExceptionextendsInvalidExtensionException{privatestaticfinallongserialVersionUID=1L;publicInvalidFlashExtensionException(String[]allowedExtension,Stringextension,Stringfilename){super(allowedExtension,extension,filename);}}publicstaticclassInvalidMediaExtensionExceptionextendsInvalidExtensionException{privatestaticfinallongserialVersionUID=1L;publicInvalidMediaExtensionException(String[]allowedExtension,Stringextension,Stringfilename){super(allowedExtension,extension,filename);}}publicstaticclassInvalidVideoExtensionExceptionextendsInvalidExtensionException{privatestaticfinallongserialVersionUID=1L;publicInvalidVideoExtensionException(String[]allowedExtension,Stringextension,Stringfilename){super(allowedExtension,extension,filename);}}}

8.BaseException.java

packagecom.springcloud.blog.admin.exception;/***基础异常**@authoryoucong*/publicclassBaseExceptionextendsRuntimeException{privatestaticfinallongserialVersionUID=1L;/***所属模块*/privateStringmodule;/***错误码*/privateStringcode;/***错误码对应的参数*/privateObject[]args;/***错误消息*/privateStringdefaultMessage;publicBaseException(Stringmodule,Stringcode,Object[]args,StringdefaultMessage){this.module=module;this.code=code;this.args=args;this.defaultMessage=defaultMessage;}publicBaseException(Stringmodule,Stringcode,Object[]args){this(module,code,args,null);}publicBaseException(Stringmodule,StringdefaultMessage){this(module,null,null,defaultMessage);}publicBaseException(Stringcode,Object[]args){this(null,code,args,null);}publicBaseException(StringdefaultMessage){this(null,null,null,defaultMessage);}publicStringgetModule(){returnmodule;}publicStringgetCode(){returncode;}publicObject[]getArgs(){returnargs;}publicStringgetDefaultMessage(){returndefaultMessage;}}二、单文件上传代码

@PostMapping("/post/uploadFile")@ApiOperation("文章上传特色图片")publicResponseBaseDTO<String>uploadFile(@RequestParam("file")MultipartFilefile){logger.info("/post/uploadFile");try{StringfileUrl=FileUploadUtils.upload(file);if(fileUrl!=null){returnResponseBaseDTO.createSuccResp(fileUrl);}returnResponseBaseDTO.createFailResp(fileUrl);}catch(Exceptione){logger.error("/post/uploadFile",e);returnResponseBaseDTO.createFailResp(e.getMessage());}}三、多文件上传代码

@PostMapping("/batchImportsUsers")@ApiOperation("批量导入用户数据小时")publicResponseBaseDTO<String>batchImportsUsers(MultipartFile[]uploadFiles){if(uploadFiles.length>0){for(inti=0;i<uploadFiles.length;i++){try{importUserExcelData(uploadFiles[i]);}catch(Exceptione){e.printStackTrace();}}returnResponseBaseDTO.createSuccResp();}returnResponseBaseDTO.createFailResp(e.getMessage());}

读到这里,这篇“Java怎么实现SpringBoot单文件和多文件的上传功能”文章已经介绍完毕,想要掌握这篇文章的知识点还需要大家自己动手实践使用过才能领会,如果想了解更多相关内容的文章,欢迎关注亿速云行业资讯频道。