You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Spring Boot从浏览器读取文件?及localhost:8181 403错误解决

嘿,我来帮你搞定这两个Spring Boot相关的问题~

一、Spring Boot实现从浏览器读取文件(文件上传)的方法

其实就是实现文件上传功能,这里给你一步步拆解:

  • 第一步:写后端Controller处理上传请求
    先创建一个Controller类,专门处理前端传过来的文件,代码示例如下:

    import org.springframework.web.bind.annotation.PostMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.bind.annotation.RestController;
    import org.springframework.web.multipart.MultipartFile;
    import java.io.File;
    import java.io.IOException;
    
    @RestController
    public class FileUploadController {
    
        @PostMapping("/upload")
        public String uploadFile(@RequestParam("file") MultipartFile file) {
            // 先检查有没有选文件
            if (file.isEmpty()) {
                return "请先选择要上传的文件哦";
            }
    
            // 定义文件保存的路径,这里用项目根目录下的uploads文件夹,你可以按需修改
            String uploadDir = System.getProperty("user.dir") + "/uploads/";
            File dir = new File(uploadDir);
            if (!dir.exists()) {
                dir.mkdirs(); // 目录不存在就创建
            }
    
            // 获取文件名并拼出完整路径
            String fileName = file.getOriginalFilename();
            String filePath = uploadDir + fileName;
    
            try {
                // 把文件存到指定路径
                file.transferTo(new File(filePath));
                return "文件上传成功啦!路径是:" + filePath;
            } catch (IOException e) {
                e.printStackTrace();
                return "文件上传失败了:" + e.getMessage();
            }
        }
    }
    
  • 第二步:写个前端页面测试(可选)
    如果需要可视化测试,在src/main/resources/templates下建一个upload.html(要用Thymeleaf的话,得先加依赖):

    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
        <meta charset="UTF-8">
        <title>文件上传测试</title>
    </head>
    <body>
        <h3>选择文件上传</h3>
        <form action="/upload" method="post" enctype="multipart/form-data">
            <input type="file" name="file" />
            <button type="submit">上传</button>
        </form>
    </body>
    </html>
    

    Maven项目的话,在pom.xml加Thymeleaf依赖:

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    
  • 第三步:配置文件大小限制(可选)
    如果怕用户传太大的文件,在application.properties里加配置:

    # 单个文件最大允许10MB
    spring.servlet.multipart.max-file-size=10MB
    # 整个请求的总大小(多文件上传时)最大20MB
    spring.servlet.multipart.max-request-size=20MB
    
二、解决localhost:8181的403 Forbidden和Whitelabel Error Page问题

先给你分析下:403是权限被拒,大概率是Spring Security搞的;Whitelabel是默认错误页,因为你没自定义错误映射。

  • 搞定403访问被拒
    如果你的项目加了Spring Security依赖,默认会拦截所有请求要求认证。你得配置放行你需要的路径,比如上传接口、测试页面这些。建个Security配置类:

    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.security.config.annotation.web.builders.HttpSecurity;
    import org.springframework.security.web.SecurityFilterChain;
    
    @Configuration
    public class SecurityConfig {
    
        @Bean
        public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
            http
                .authorizeHttpRequests(auth -> auth
                    // 放行上传接口、测试页面、根路径这些
                    .requestMatchers("/upload", "/upload.html", "/").permitAll()
                    // 其他请求需要登录认证
                    .anyRequest().authenticated()
                )
                // 测试环境可以先关csrf,生产环境记得开
                .csrf(csrf -> csrf.disable());
            return http.build();
        }
    }
    

    要是没用到Spring Security,那可能是你自己写的拦截器或者过滤器挡了请求,得去检查拦截规则哦。

  • 替换掉Whitelabel默认错误页
    有两种简单的方式:

    1. 静态错误页:在src/main/resources/static/error文件夹下建对应状态码的HTML,比如403.html:
      <!DOCTYPE html>
      <html lang="zh-CN">
      <head>
          <meta charset="UTF-8">
          <title>访问被拒绝</title>
      </head>
      <body>
          <h1>403 - 抱歉,你没有权限访问这个页面</h1>
          <p>可以联系管理员申请权限哦~</p>
      </body>
      </html>
      
      Spring Boot会自动根据返回的状态码匹配对应的页面。
    2. 自定义错误控制器:写个类处理/error路径的请求,自定义返回内容:
      import org.springframework.boot.web.servlet.error.ErrorController;
      import org.springframework.web.bind.annotation.GetMapping;
      import org.springframework.web.bind.annotation.RestController;
      
      @RestController
      public class CustomErrorController implements ErrorController {
      
          @GetMapping("/error")
          public String handleError() {
              return "哎呀,访问出错了!请检查你的请求路径或者联系管理员~";
          }
      }
      

内容的提问来源于stack exchange,提问作者Avinash Jadhav

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 06:46:10