博主最近在学 elment Ui 所以 前端使用 elmentUi 的 upload 组件实现
引入 elmentUi 的 css 和 js
我们采用官网的这种方式 cdn 的方式
项目的目录结构:
搭建前端页面
光这些肯定不够 我们还需要前后端交互的页面
测试文件上传
找到 pom.xml
spring-boot-starter-parent
org.springframework.boot
2.5.0
8
8
UTF-8
org.springframework.boot
spring-boot-starter-web
controller
/**
* @author : look-word
* 2022-06-27 22:28
**/
@RestController
public class FileController {
/**
* 设置/img/**的访问规则
* 意思就是当我们访问 http://localhost:8899/img/redis.png的时候
* 会去addResourceLocations这和目录下寻找
*/
@Configuration
public static class MyPicConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/img/**")
.addResourceLocations("file:"+System.getProperty("user.dir") + "\src\main\resources\static\img\");
}
}
/**
* 接收上传文件的接口
* @param urlFile 上传的文件
* @param request 请求
* @return
*/
@PostMapping("/upload")
public String upload(@RequestParam("file") MultipartFile urlFile,HttpServletRequest request) {
// url =》 http://localhost:8899/upload
StringBuffer url = request.getRequestURL();
// 意思是 取出ip地址加端口 http://localhost:8899
String baseUrl = url.substring(0, url.length() - (url.length() - url.lastIndexOf("/")));
// 文件名称
String fileName = System.currentTimeMillis() + urlFile.getOriginalFilename();
// 文件存储的路径
String filePath = System.getProperty("user.dir") + "\src\main\resources\static\img\";
File file = new File(filePath);
// 当文件夹不存在 创建文件夹
if (!file.exists()) {
file.mkdir();
}
File dest = new File(filePath + fileName);
String storeUrlPath = "/img/" + fileName;
try {
// 写到文件夹中
urlFile.transferTo(dest);
System.out.println("上传成功");
} catch (IOException e) {
System.out.println("上传失败");
throw new RuntimeException(e);
}
return baseUrl+storeUrlPath;
}
}
我们现在接收上传文件的接口 打上断点 下面一步一步解析里面的代码
这样就上传成功啦 那么 我们该如何去访问这个图片呢?
来到这里 当我们访问的资源文件路径为/img开头的时候 会默认 去到"file:"+System.getProperty("user.dir") + "\src\main\resources\static\img\"来寻找 就是我们项目的静态资源文件夹的位置
可以看到 当我们 上传成功后 资源成功地展示到了 我们的页面上
原文: https://www.cnblogs.com/look-word/p/16419141.html
留言与评论(共有 0 条评论) “” |