java将上传文件保存数据库,后端返回文件给前端
上传工具类
importorg.Apache.com mons.lang.string utils; importorg.spring framework.web.multipart.multipart file; import java.io.File; import java.io.IOException; import java.util.Date;/* * @ auther : hys * @ date :2021/8/2612336029 * @ description :是本地服务器*/publiccclassfileuploadutil {//23: 将文件上载到并保存的linux服务器路径//privatestaticfinalstringupload _ path='/usr/local/picture/'; //文件类型privatefinalstaticstringvideo _ type _ avi=' avi '; privatefinalstaticstringvideo _ type _ MP4=' MP4 '; privatefinalstaticstringvideo _ type _ wmv=' wmv '; 私有金融服务视频_ type _ mpg=' mpg '; privatefinalstaticstringvideo _ type _ mpeg=' mpeg '; privatefinalstaticstringvideo _ type _ mov=' mov '; //publicstaticstringupload (多路径文件) throwsboexception (stringfileoriginname=file.getoriginalfilename ) is图片(获取曲面文件名称) ({ throw new BOException )视频格式仅支持avi、mp4、wmv、mpg、mpeg和mov格式); } string filename=string.format (' % s-% s.% s ',creditutils.dateformart ) newdate ),' yyyyMMdd ',creditutils //如果路径中不存在创建路径if (! dest.getParentFile(.exists ) ) dest.getparentfile ).mkdirs ); (try ) file.transferto ) ) dest; }catch(ioexceptione ) { e.printStackTrace ); throw new BOException ('图像上传失败'); //在数据库中存储和访问此路径时,从http://IP :端口/文件路径/文件名访问返回' /文件路径/'文件名; } /** *文件的后缀* @ param filename * @ return */publicstaticstringgetsuffix (返回文件名称. substring 确认文件格式正确* @ param suffix * @ return */publicstaticbooleanispicture (string suffix ) { boolean flag=false; if(stringutils.isblank(suffix ) ) { return false; } if (video _ type _ avi.equals ignore case (suffix )|video _ type _ MP4.equals ignore case ) suffix|video _ MP4 . video _ ignore video _ type _ mpg.equals ignore case|| video _ type _ mpeg.equals ignore case|| video _ type _ equale }} Controller控制层
/** *上传视频文件* @ paramfile * @ return * @ throwsboexception */@ request mapping (value='/upload video ' ), method=request method.post (响应性bodypublicstringuploadvideo ) requestparam ) value='file ', required=true (多文件) throwsboexception(if ) file.isempty ) {throw new BOException '上传文件不能为空}LOG.info ('上传文件大小: ' file.getSize ) ); if (文件. getsize (20 * 1024 * 1024 ) ) {throw new BOException )上传文件为20M ) ); } returnfileuploadutil.upload (file; } 资源映射
importorg.spring帧work.context.annotation.bean; importorg.spring framework.context.annotation.configuration; importorg.spring framework.web.servlet.config.annotation.resourcehandlerregistry; importorg.spring framework.web.servlet.config.annotation.webmvcconfigureradapter;/* * @ auther : hys * @ date :2021/8/2611336014 * @ description : */@ configurationpublicclasswebmvcconfigurerextendswebmvcconfigureradapter { @ overridepublicvoidaddresourcehandlers (资源harce handler(/filepath/** ' ).addresourcelocations ) ) file:f:/picture/' ); }