当前位置: 首页 > Web前端 > vue.js

VueSpringBoot文件操作、上传、预览、删除

时间:2023-03-31 18:07:43 vue.js

视频演示:https://www.bilibili.com/video/BV1VK4y1s7b1/需要完成以下步骤:创建一个项目,引入依赖包spring-boot-starter-weblok进行文件操作,上传预览删除删除添加跨域功能前端使用VUE,前后端分离看不懂代码,不建议下载可以参考上一篇,文件上传采用Form方式(前后端不分离)FileUploadController.javapackagecom.example.spring.fileupload;importorg.springframework.beans.factory.annotation。自动装配;导入org.springframework.beans.factory.annotation.Value;导入org.springframework.core.io.Resource;导入org.springframework.core.io.UrlResource;导入org.springframework.http.HttpHeaders;导入org.springframework.http.ResponseEntity;导入org.springframework.util.FileSystemUtils;导入org.springframework.util.StringUtils;导入org。springframework.web.bind.annotation.*;导入org.springframework.web.multipart.MultipartFile;导入org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder;导入java.io.IOException;导入java.net。MalformedURLException;我端口java.nio.file.Files;导入java.nio.file.Path;导入java.nio.file.Paths;导入java.nio.file.StandardCopyOption;导入java.util.List;导入java.util.stream。Collectors;@RestControllerpublicclassFileUploadController{//上传文件路径@Value("${file.base.director}")privateStringfileBaseDirector;私有路径fileBasePath;@AutowiredprivatevoidcreateDirectories(){try{Files.createDirectories(Paths.get(fileBaseDirector));}catch(IOExceptione){e.printStackTrace();}this.fileBasePath=Path.of(fileBaseDirector);}@GetMapping("/loadAll")publicResponseEntityloadAll()抛出IOException{ListfilesAll=Files.walk(fileBasePath,1).filter(path->!path.equals(fileBasePath)).map(path->{字符串url=MvcUriComponentsBuilder.fromMethodName(FileUploadController.class,"loadFile",path.getFileName().toString()).build().toString();FileObjectfileObject=newFileObject(path.getFileName().toString(),url);返回文件对象;}).collect(Collectors.toList());返回ResponseEntity.ok(filesAll);}@DeleteMapping("delete/{fileName}")publicResponseEntitydeleteFile(@PathVariableStringfileName){PathdeletePath=fileBasePath.resolve(fileName);BooleanisDelete=Boolean.FALSE;try{isDelete=FileSystemUtils.deleteRecursively(deletePath);}catch(IOExceptione){e.printStackTrace();}返回ResponseEntity.ok(isDelete);}@GetMapping("/{fileName}")publicResponseEntityloadFile(@PathVariableStringfileName){路径path=fileBasePath.resolve(fileName);资源resource=null;尝试{resource=newUrlResource(path.toUri());}赶上(畸形dURLExceptione){e.printStackTrace();}returnResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION,"attachment;filename=\""+resource.getFilename()+"\"").body(resource);}@PostMapping("/upload")publicResponseEntityupload(@RequestParam("file")MultipartFilefile){StringfileName=StringUtils.cleanPath(file.getOriginalFilename());路径path=Path.of(fileBaseDirector+fileName);试试{Files.copy(file.getInputStream(),path,StandardCopyOption.REPLACE_EXISTING);}catch(IOExceptione){e.printStackTrace();}返回ResponseEntity.ok("确定");}}