springboot+vue 上传图片到本地文件夹,并在前端显示(已解决)

我遇到的问题是存到本地文件夹了以后,无法在前端显示:

GET http://localhost:8080/files/abc9fc42-55c8-4f15-9dcd-06d43757c1ed.png 401 (Unauthorized)

 我的拦截器 LoginInterceptor 会拦截 /files/** 请求,放行  /files/**  就行了

 仅修改:

public void addInterceptors(InterceptorRegistry registry) {
    // 注册拦截器
    // 登录和注册接口不拦截
    registry.addInterceptor(loginInterceptor).excludePathPatterns("/user/login", "/user/register", "/files/**");
}

FileUploadController.java:

@RestController
public class FileUploadController {

    @PostMapping("/upload")
    public Result<String> upload(MultipartFile file) throws IOException{



        //获取文件内容的输入流,写入到本地磁盘文件
        String originalFilename = file.getOriginalFilename();
        //要保证文件名字唯一的,从而防止文件覆盖
        String filename = UUID.randomUUID().toString()+originalFilename.substring(originalFilename.lastIndexOf("."));
        // 保存路径
        String savePath = "G:\\springbootFiles\\" + filename;
        file.transferTo(new File(savePath));

        // 这里需要替换成你前端访问的URL路径,比如你的后端服务器是 http://localhost:8080
        String fileUrl = "http://localhost:8080/files/" + filename;

        return Result.success(fileUrl);
    }
}

  WebConfig.java:

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Autowired
    private LoginInterceptor loginInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 注册拦截器
        // 登录和注册接口不拦截
        registry.addInterceptor(loginInterceptor).excludePathPatterns("/user/login", "/user/register", "/files/**");
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 访问 http://localhost:8080/files/xxx.jpg 时,映射到 G:\springbootFiles\ 目录下
        registry.addResourceHandler("/files/**")
                .addResourceLocations("file:G:/springbootFiles/");
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值