一、访问静态资源:
在application.properties添加
spring.mvc.static-path-pattern=/**
如此程序便可访问到static/img 文件,访问路径:http://localhost:端口号/img/s01.png
二、上传图片到指定位置进行访问:
WebConfig WebMvcConfigurer { AuthInterceptor String = (InterceptorRegistry registry) { registry.addInterceptor().addPathPatterns()} (ResourceHandlerRegistry registry) { registry.addResourceHandler().addResourceLocations(+)} }
如此便可通过http://localhost:端口号/项目/upload/2023/11/19/e456829e-9b96-4dcc-8dab-fafa9c12769c.jpg 访问。
下面是上传图片代码:
jakarta.servlet.http.HttpServletRequestorg.springframework.web.bind.annotation.org.springframework.web.bind.annotation.org.springframework.web.bind.annotation.org.springframework.web.bind.annotation.org.springframework.web.multipart.MultipartFilejava.io.Consolejava.io.Filejava.io.IOExceptionjava.text.SimpleDateFormatjava.util.ArrayListjava.util.Datejava.util.Listjava.util.UUID() FileController { SimpleDateFormat = SimpleDateFormat()() Result (() MultipartFile uploadFileHttpServletRequest req) { String realPath = System..println(realPath)System..println(realPath)String format = .format(Date())File folder = File(realPath + format)(!folder.isDirectory()) { folder.mkdirs()} String oldName = uploadFile.getOriginalFilename()String newName = UUID.().toString() + oldName.substring(oldName.lastIndexOf()oldName.length()){ uploadFile.transferTo(File(foldernewName))String filePath = + format + newNameResult result = Result()Data data = Data()data.setSrc(filePath)result.setCode()result.setData(data)result.setMsg()result} (IOException e) { e.printStackTrace()} Result result = Result()result.setCode()result.setMsg()result} Result<> { String () { } (code) { .= code} String () { } (String msg) { .= msg} () { } (data) { .= data} } Data { String String () { } (String src) { .= src} } }