网页设计站点建设实验报告,上海网站建设 网络推广,上海网站推广有哪些,个人网站制作申请前言
本文将实现在数据库中存储图片url#xff0c;url可以在浏览器中访问查看。 整体思路为#xff1a;
上传图片到本地指定地址为图片分配url保存至数据库根据分配url#xff0c;进行物理地址映射到本地指定地址
具体实现
controller层#xff1a; 上传图片到本地指定…前言
本文将实现在数据库中存储图片urlurl可以在浏览器中访问查看。 整体思路为
上传图片到本地指定地址为图片分配url保存至数据库根据分配url进行物理地址映射到本地指定地址
具体实现
controller层 上传图片到本地指定地址为图片分配url保存至数据库
PostMapping(/uploadImg)Operation(summary 上传图片)public ResultString upload(MultipartFile file, HttpServletRequest request) {String subPath \\upload\\Img\\;String basepath webFileUrl;String path ;String vpath ;String fileType ;MapString, Object resultPath WebFileUtils.saveFile(file, basepath subPath, request);path resultPath.get(path).toString();fileType resultPath.get(fileType).toString();vpath /statics/upload/ Img / fileType / new File(path).getName();return R2.ok(vpath,上传成功);}其中的WebFileUtils类
public static MapString, Object saveFile(MultipartFile file, String webFileUrl, HttpServletRequest request) {System.out.println();String realPath, rootPath webFileUrl;if (webFileUrl.equals()) {//设置主路径realPath request.getServletContext().getRealPath();//将路径设置到当前项目同级并创建upload文件夹rootPath new File(realPath).getParent() \\upload\\;}//组合文件名String filename System.currentTimeMillis() _ file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(\\) 1);//获取文件后缀String extension . FilenameUtils.getExtension(filename);//生成新的文件名String newFileName new SimpleDateFormat(yyyyMMddHHmmss).format(new Date()) UUID.randomUUID().toString().replace(-,) extension;// 区分上传文件是图片还是视频String fileType;FileNameMap fileNameMap URLConnection.getFileNameMap();String contentTypeFor fileNameMap.getContentTypeFor(filename);if (contentTypeFor null){fileType video;rootPath rootPath \\ fileType \\;}else{fileType image;rootPath rootPath \\ fileType \\;}String filePath rootPath newFileName;File localFile new File(filePath);// 检测是否存在目录不存在则创建if (!localFile.getParentFile().exists()) {localFile.getParentFile().mkdirs();}try {//保存文件file.transferTo(localFile);} catch (IOException e) {e.printStackTrace();}MapString,Object result new MapUtils();result.put(path, localFile.getAbsolutePath());result.put(fileType, fileType );//返回文件的绝对路径return result;}此处webFileUrl替换为上传文件本地保存地址。
config 在此处完成物理地址映射到本地指定地址
Configuration
public class UploadConfig implements WebMvcConfigurer {Overridepublic void addResourceHandlers(ResourceHandlerRegistry registry) {registry.addResourceHandler(/api/statics/upload/Img/image/**).addResourceLocations(file:本地保存地址);}
}至此如果需要实现前端图片预览查看功能请求数据库中保存的图片url即可。