网站服务器租用价格 贴吧,广州建设行业网站,如何做网站自适应,大型电商平台有哪些实现文件上传和回显1、新建一个SpringBoot项目#xff0c;选择 Spring Web 和 thymeleaf 依赖 。pow.xml文件下的依赖如下2、根据下图#xff0c;创建如下文件3、直接上代码配置文件 application.xmlserver:port: 8005file:upload:path: F://upload/relationImg: /images/配置…实现文件上传和回显1、新建一个SpringBoot项目选择 Spring Web 和 thymeleaf 依赖 。pow.xml文件下的依赖如下2、根据下图创建如下文件3、直接上代码配置文件 application.xmlserver:port: 8005file:upload:path: F://upload/relationImg: /images/配置类 MyWenMvcConfigurer.java/**资源映射路径*/Configurationpublic class MyWebMvcConfigurer implementsWebMvcConfigurer {/**保存的真实地址*/Value(${file.upload.path})String sysPath;/**请求的相对地址*/Value(${file.upload.relationImg})String relationImg;Overridepublic voidaddResourceHandlers(ResourceHandlerRegistry registry) {/**将相对地址映射到真实地址*/registry.addResourceHandler(relationImg**).addResourceLocations(file:/sysPathrelationImg);}}服务层接口 UploadService.javapublic interfaceUploadService {/**保存文件并返回文件的相对路径*/publicString uploadImg(MultipartFile file);}服务层实现类 UploadServiceImpl.javaServicepublic class UploadServiceImpl implementsUploadService {Value(${file.upload.path})String sysPath;Value(${file.upload.relationImg})String relationImg;OverridepublicString uploadImg(MultipartFile file) {//uuid生成的唯一前缀 上传文件名 构成唯一的新文件名String fileName UUID.randomUUID()_file.getOriginalFilename();//文件保存路径String pathsysPathrelationImg;//新建文件filepathFile filepathnewFile(path,fileName);//判断路径是否存在如果不存在就创建一个if(!filepath.getParentFile().exists()){filepath.getParentFile().mkdirs();}try{//将上传的文件file写入文件filepathfile.transferTo(new File(pathFile.separatorfileName));}catch(IOException e){e.printStackTrace();}//将请求文件的相对路径返回return relationImgfileName;}}控制类 UploadController.javaControllerpublic classUploadController {AutowiredUploadService uploadService;GetMapping(/uploadImg)publicString getuploadImg(){return /upload/uploadImg;}PostMapping(/uploadImg)public String uploadImg(RequestParam(file)MultipartFile file, Model model){String imgUrluploadService.uploadImg(file);model.addAttribute(imgUrl,imgUrl);return /upload/uploadImg;}}视图层 uploadImg.html图片上传并回显图片地址[[${imgUrl}]]效果图真实保存路径F:\upload\images注意下面两张图的名字第一张多了的前缀就是 UUID.randomUUID() 生成的为了保证文件名的唯一性单文件上传控制层 FileController.javaControllerpublic classFileController {//单文件上传页面跳转GetMapping(/singleUpload)publicString singleUpload(){return singleUpload;}//单文件上传管理PostMapping(/singleUploadFile)public String singleUploadFile(HttpServletRequest httpServletRequest, MultipartFile file, Model model) throwsIOException {//获取文件名以及后缀名String fileNamefile.getOriginalFilename();//重新生成文件名(根据具体情况生成对应文件名)fileName UUID.randomUUID()_fileName;//指定上传文件本地存储目录不存在需要提前创建String dirPathF:/file/;File filePathnewFile(dirPath);//指定上传文件本地存储目录不存在需要提前创建if(!filePath.exists()){filePath.mkdirs();}try{//将文件写入磁盘file.transferTo(newFile(dirPath,fileName));model.addAttribute(uploadStatus,上传成功);}catch(Exception e){e.printStackTrace();model.addAttribute(uploadStatus,上传失败e.getMessage());}//将带上传状态信息回调到文件上传页面return singleUpload;}}singleUpload.html单文件上传上传成功!