目录
我们知道文件的上传就是把本地的文件上传到服务器上(在服务器中指定地址保存);通过访问服务器地址去查看文件;但是直接通过域名和保存地址是无法访问到上传的文件!需要使用映射来帮助我们查看上传到服务器中的文件!
效果:
1、调用/upload接口,上传名为1.jpg的图片;接口返回服务器映射后的url地址;
2、访问返回的地址即可看到图片信息;
- import com.chensir.interceptor.TokenInterceptor;
- import org.springframework.beans.factory.annotation.Value;
- import org.springframework.context.annotation.Configuration;
- import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
- import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
- import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
-
- /**
- * @author ChenSir
- * @Date 2023/9/20
- **/
- @Configuration
- public class WebConfig implements WebMvcConfigurer {
-
- @Value("${chensir.path.upload}")
- private String upload;
-
-
- @Override
- public void addResourceHandlers(ResourceHandlerRegistry registry) {
- //和页面有关的静态目录都放在项目的static目录下
- // registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
-
- //upload是图片保存的地址,详细地址在配置文件中; "file:" + upload 是文件真实的存储路径; "/photos/**"是映射访问地址,通过访问
- //http://localhost:8081/photos/d3cf0281-bb7f-40e0-ab77-406db95ccf2c.jpg 即可访问到图片
- registry.addResourceHandler("/photos/**").addResourceLocations("file:" + upload);
- }
- }
- package com.chensir.system.controller;
-
- import lombok.extern.slf4j.Slf4j;
- import org.springframework.beans.factory.annotation.Value;
- import org.springframework.web.bind.annotation.*;
- import org.springframework.web.multipart.MultipartFile;
-
- import javax.servlet.http.HttpServletResponse;
- import java.io.File;
- import java.io.IOException;
- import java.util.HashMap;
- import java.util.Map;
- import java.util.UUID;
-
- /**
- * 文件上传
- *
- * @author ChenSir
- * @Date 2023/10/9
- **/
- @RestController
- @Slf4j
- public class FileController {
-
- @Value("${chensir.path.upload}")
- private String photoPath;
-
- @Value("${chensir.url.prefix}")
- private String filePrefix;
-
- @PostMapping("/upload")
- public String insertOrderImg(@RequestParam("file") MultipartFile file, HttpServletResponse response) {
- // 返回Map
- Map
resultMap = new HashMap<>(); - String imgUrl =null;
- // 文件上传路径
- //String location = "D:\\photos\\"; //TODO 改为服务器路径
- String location = photoPath;
- if (!file.isEmpty()) {
- // 获取文件原始名称 a.png -> a
- String originalFilename = file.getOriginalFilename();
- // 获取文件后缀 .png
- String extName = originalFilename.substring(originalFilename.lastIndexOf("."));
-
- //设置允许上传文件类型
- String suffixList = ".jpg,.png,.ico,.bmp,.jpeg,.pdf,.docx,.webp";
- // 判断是否包含
- if (suffixList.contains(extName.trim().toLowerCase())) {
- // 保存文件的路径
- String fileName = UUID.randomUUID() + extName;
- String path = location + fileName;
-
- // 查看路径是否存在,不存在就创建
- //image/jpeg
- if (!new File(path).exists()) {
- boolean mkdirs = new File(path).mkdirs();
- }
- // spring的transferTo保存文件方法
- try {
- file.transferTo(new File(path));
- imgUrl = filePrefix + fileName;
-
- } catch (IOException e) {
- e.printStackTrace();
- log.error("上传文件出错!");
-
- }
- }
- } else {
- resultMap.put("code", "500");
- resultMap.put("msg", "未选择图片!");
- resultMap.put("data", "");
- }
- return imgUrl;
- }
- }
- package com.chensir.system.controller;
-
- import com.chensir.result.R;
- import lombok.extern.slf4j.Slf4j;
- import org.springframework.beans.factory.annotation.Value;
- import org.springframework.web.bind.annotation.*;
- import org.springframework.web.multipart.MultipartFile;
-
- import javax.servlet.http.HttpServletResponse;
- import java.io.File;
- import java.io.IOException;
- import java.util.HashMap;
- import java.util.Map;
- import java.util.UUID;
-
- /**
- * 文件上传
- *
- * @author ChenSir
- * @Date 2023/10/9
- **/
- @Slf4j
- @RestController
- public class FileController {
-
- @Value("${chensir.path.upload}")
- private String photoPath;
-
- @Value("${chensir.url.prefix}")
- private String filePrefix;
-
- @PostMapping("/upload")
- public R insertOrderImg(@RequestParam("file") MultipartFile file, HttpServletResponse response) {
- // 返回Map
- Map
resultMap = new HashMap<>(); - String imgUrl = null;
- // 文件上传路径
- String location = photoPath;
- if (!file.isEmpty()) {
- // 获取文件原始名称 a.png -> a
- String originalFilename = file.getOriginalFilename();
- // 获取文件后缀 .png
- String extName = originalFilename.substring(originalFilename.lastIndexOf("."));
-
- //设置允许上传文件类型
- String suffixList = ".jpg,.png,.ico,.bmp,.jpeg,.pdf,.docx,.webp";
- // 判断是否包含
- if (suffixList.contains(extName.trim().toLowerCase())) {
- // 保存文件的路径
- String fileName = UUID.randomUUID() + extName;
- String path = location + fileName;
-
- // 解析成为绝对路径
- File dest = new File((new File(path).getAbsolutePath()));
-
- // 查看路径是否存在,不存在就创建
- //image/jpeg
- if (!new File(path).exists()) {
- // boolean mkdirs = new File(path).mkdirs();
-
- dest.getParentFile().mkdirs();
- }
- // spring的transferTo保存文件方法
- try {
- // file.transferTo(new File(path));
- file.transferTo(dest);
- imgUrl = filePrefix + fileName;
- } catch (IOException e) {
- e.printStackTrace();
- log.error("上传文件出错!");
- }
- }
- return R.ok(imgUrl);
- } else {
- resultMap.put("code", "500");
- resultMap.put("msg", "未选择图片!");
- resultMap.put("data", "");
- return R.fail(resultMap);
- }
- }
- }