4bb2c776-67cf-4c20-8bbe-720da0216d55.jpeg

图片上传

现在想要去上传一张照片,首先前端调用上传接口

/**
 * xx图片上传
 */
@PostMapping("/avatar")
public AjaxResult avatar(@RequestParam("avatarfile") MultipartFile file) throws IOException
{
    if (!file.isEmpty()){
        // ...
        String avatar = FileUploadUtils.upload(RuoYiConfig.getAvatarPath(), file);
        if (userService.updateUserAvatar(loginUser.getUsername(), avatar))
        {
            AjaxResult ajax = AjaxResult.success();
            ajax.put("imgUrl", avatar);
            // ...
            return ajax;
        }
    }
    return AjaxResult.error("上传图片异常,请联系管理员");
}

保存到数据库,并返回给前端

{
	code: 200
	imgUrl: "/profile/avatar/2021/06/17/6bbf9ba0-5341-4bc1-8af2-0943ec9aa530.jpeg"
	msg: "操作成功"
}

web前端将其拼接,就可以访问到服务器上的本地文件
http://localhost/dev-api/profile/avatar/2021/06/17/xxx.jpeg

图片路径


前端

可以看到图片路径有点陌生,这里使用到了代理;路径首先被web前端解析

-- 前端配置
process.env.VUE_APP_BASE_API = 'http://localhost/dev-api'

-- 使用代理来解决跨域问题
http://localhost/dev-api -> http://localhost:8080

-- 解析前端请求 /dev-api
http://localhost/dev-api/profile/avatar/2021/06/17/xxx.jpeg
-- 此时,再将请求交给后端处理
http://localhost:8080/profile/avatar/2021/06/17/xxx.jpeg		

后端

后端对匹配的URL进行拦截 /profile/** ,映射至本地文件夹 RuoYiConfig.getProfile()

/**
 * 通用配置
 * 
 * @author ruoyi
 */
@Configuration
public class ResourcesConfig implements WebMvcConfigurer
{
	/** 配置静态资源映射 */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry)
    {
        /** 本地文件上传路径 */
        registry.addResourceHandler(Constants.RESOURCE_PREFIX + "/**").addResourceLocations("file:" + RuoYiConfig.getProfile() + "/");
		// ...
    }
    // ...
}

相关常量

# 资源映射路径 前缀
Constants.RESOURCE_PREFIX = "/profile"

# RuoYiConfig.getProfile() 获取项目信息 ruoyi.profile
D:/ruoyi/uploadPath

这样图片数据便被从本地拿到,经历了 前端 -> 后端 -> 本地文件 的过程!

Logo

快速构建 Web 应用程序

更多推荐