SpringBoot实现文件上传接口
摘要
公司都是采用SpringBoot作为项目框架,其实SpringBoot和SSM框架很接近,基本上只是将SSM的一些配置项修改为自动配置或者简单的注解配置就可以了,建议不了解的SpringBoot的朋友们可以了解一下,上手很快,其实文件上传框架根本没有多大关系。我只是顺便帮SpringBoot打个广告罢了。
正题
需求:需要实现一个文件上传的web接口。
1、先实现一个Controller接口,如下:
packagecom.lanxuewei.utils.aspect;
importcom.lanxuewei.utils.interceptor.annotation.AppIdAuthorization;
importcom.lanxuewei.utils.model.ReturnCodeAndMsgEnum;
importcom.lanxuewei.utils.model.ReturnValue;
importorg.slf4j.Logger;
importorg.slf4j.LoggerFactory;
importorg.springframework.beans.factory.annotation.Autowired;
importorg.springframework.web.bind.annotation.RequestMapping;
importorg.springframework.web.bind.annotation.RequestParam;
importorg.springframework.web.bind.annotation.RestController;
importorg.springframework.web.multipart.MultipartFile;
/**
*@authorlanxueweiCreatein2018/7/320:01
*Description:aop测试控制器
*/
@RestController
@RequestMapping(value="/aop")
publicclassTestController{
privatestaticfinalLoggerlogger=LoggerFactory.getLogger(TestController.class);
@Autowired
privateTestServicetestService;
/**
*文件上传测试接口
*@return
*/
@AppIdAuthorization
@RequestMapping("/upload")
publicReturnValueuploadFileTest(@RequestParam("uploadFile")MultipartFilezipFile){
returntestService.uploadFileTest(zipFile);
}
}
2、Service接口如下:
packagecom.lanxuewei.utils.aspect;
importorg.springframework.web.multipart.MultipartFile;
importcom.lanxuewei.utils.model.ReturnValue;
publicinterfaceTestService{
publicReturnValueuploadFileTest(MultipartFilezipFile);
}
3、Service实现如下:
packagecom.lanxuewei.utils.aspect;
importcom.lanxuewei.utils.model.ReturnCodeAndMsgEnum;
importcom.lanxuewei.utils.model.ReturnValue;
importorg.apache.commons.io.IOUtils;
importorg.slf4j.Logger;
importorg.slf4j.LoggerFactory;
importorg.springframework.stereotype.Service;
importorg.springframework.web.multipart.MultipartFile;
importjava.io.File;
importjava.io.FileOutputStream;
importjava.io.IOException;
importjava.util.UUID;
/**
*@authorlanxueweiCreatein2018/8/1410:01
*Description:
*/
@Service
publicclassTestServiceImpimplementsTestService{
privatestaticfinalLoggerlogger=LoggerFactory.getLogger(TestServiceImp.class);
@Override
publicReturnValueuploadFileTest(MultipartFilezipFile){
StringtargetFilePath="D:\\test\\uploadTest";
StringfileName=UUID.randomUUID().toString().replace("-","");
FiletargetFile=newFile(targetFilePath+File.separator+fileName);
FileOutputStreamfileOutputStream=null;
try{
fileOutputStream=newFileOutputStream(targetFile);
IOUtils.copy(zipFile.getInputStream(),fileOutputStream);
logger.info("------>>>>>>uploadedafilesuccessfully!<<<<<<------");
}catch(IOExceptione){
returnnewReturnValue<>(-1,null);
}finally{
try{
fileOutputStream.close();
}catch(IOExceptione){
logger.error("",e);
}
}
returnnewReturnValue<>(ReturnCodeAndMsgEnum.Success,null);
}
}
说明:
1、targetFilePath为文件保存路径,本人用于测试所以指定路径,可根据实际情况进行修改。
2、fileName采用UUID生成,保证文件名唯一不重复,但是没有保留原文件后缀,可通过获取原文件文件名后,调用lastIndexOf(“.”)获取文件原后缀加上。
3、IOUtils为org.apache.commons.io.IOUtils,注意别导入错误。
4、本文中采用logback日志系统,可根据实际情况修改或删除。
附上ReturnValue以及ReturnCodeAndMsgEnum类,用于Controller层统一返回前端的model,如下:
packagecom.lanxuewei.utils.model; importjava.io.Serializable; /** *@authorlanxueweiCreatein2018/7/320:05 *Description:统一web返回结果 */ publicclassReturnValueimplementsSerializable{ privatestaticfinallongserialVersionUID=-1959544190118740608L; privateintret; privateStringmsg; privateTdata; publicReturnValue(){ this.ret=0; this.msg=""; this.data=null; } publicReturnValue(intretCode,Stringmsg,Tdata){ this.ret=0; this.msg=""; this.data=null; this.ret=retCode; this.data=data; this.msg=msg; } publicReturnValue(intretCode,Stringmsg){ this.ret=0; this.msg=""; this.data=null; this.ret=retCode; this.msg=msg; } publicReturnValue(ReturnCodeAndMsgEnumcodeAndMsg){ this(codeAndMsg.getCode(),codeAndMsg.getMsg(),null); } publicReturnValue(ReturnCodeAndMsgEnumcodeAndMsg,Tdata){ this(codeAndMsg.getCode(),codeAndMsg.getMsg(),data); } publicintgetRet(){ returnthis.ret; } publicvoidsetRet(intret){ this.ret=ret; } publicStringgetMsg(){ returnthis.msg; } publicvoidsetMsg(Stringmsg){ this.msg=msg; } publicTgetData(){ returnthis.data; } publicvoidsetData(Tdata){ this.data=data; } @Override publicStringtoString(){ return"ReturnValue{"+ "ret="+ret+ ",msg='"+msg+'\''+ ",data="+data+ '}'; } }
packagecom.lanxuewei.utils.model;
/**
*@authorlanxueweiCreatein2018/7/320:06
*Description:web相关接口返回状态枚举
*/
publicenumReturnCodeAndMsgEnum{
Success(0,"ok"),
No_Data(-1,"nodata"),
SYSTEM_ERROR(10004,"systemerror");
privateStringmsg;
privateintcode;
privateReturnCodeAndMsgEnum(intcode,Stringmsg){
this.code=code;
this.msg=msg;
}
publicstaticReturnCodeAndMsgEnumgetByCode(intcode){
ReturnCodeAndMsgEnum[]var1=values();
intvar2=var1.length;
for(intvar3=0;var3
Postman发请求返回结果成功,以上代码只需要uploadFile一个参数即可。
注意事项:application.properties配置文件中可以配置文件上传相关属性,配置上传文件大小限制。
单个文件最大限制:spring.servlet.multipart.max-file-size=50Mb
单次请求最大限制:spring.servlet.multipart.max-request-size=70Mb
总结:本文功能较为简单,所以有些过程并没有更细致过程以及规范代码,比如存放路径采用项目路径,新文件名保持和原文件后缀一致等,需要的小伙伴可以根据自己业务进行修改。
续更,总觉得代码过于随意了,补充文件上传获得文件后缀相关函数
privateStringgetFileSuffix(MultipartFilefile){
if(file==null){
returnnull;
}
StringfileName=file.getOriginalFilename();
intsuffixIndex=fileName.lastIndexOf(".");
if(suffixIndex==-1){//无后缀
returnnull;
}else{//存在后缀
returnfileName.substring(suffixIndex,fileName.length());
}
}
在随机生成文件名后补充如下代码即可,如果返回文件后缀不为空则将其加入新产生的文件名中即可:
StringfileSuffix=getFileSuffix(zipFile);
if(fileSuffix!=null){//拼接后缀
fileName+=fileSuffix;
}
FiletargetFile=newFile(targetFilePath+File.separator+fileName);
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。