springboot的后端处理HTML的页面请求

下面是一个完整的 Spring Boot 后端示例,用于接收

提交的文件上传请求(/article/uploadLifeImage 接口),并将上传的文件保存到本地目录。


✅ 一、项目结构

upload-demo/
├── src/
│   └── main/
│       ├── java/com/example/uploaddemo/
│       │   ├── UploadDemoApplication.java
│       │   └── controller/UploadController.java
│       └── resources/
│           └── application.properties
├── pom.xml

✅ 二、依赖配置(pom.xml)


    4.0.0
    com.example
    upload-demo
    0.0.1-SNAPSHOT
    upload-demo
    Spring Boot File Upload Example

    
        17
        3.2.0
    

    
        
        
            org.springframework.boot
            spring-boot-starter-web
        
        
    

    
        
            
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    


✅ 三、配置文件(application.properties

# 设置文件上传大小限制(可选)
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB

✅ 四、主启动类(UploadDemoApplication.java)

package com.example.uploaddemo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class UploadDemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(UploadDemoApplication.class, args);
    }
}

✅ 五、控制器(UploadController.java)

package com.example.uploaddemo.controller;

import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.http.ResponseEntity;

import java.io.File;
import java.io.IOException;

@RestController
@RequestMapping("/article")
public class UploadController {

    @PostMapping("/uploadLifeImage")
    public ResponseEntity handleFileUpload(@RequestParam("upload_file") MultipartFile file) {
        if (file.isEmpty()) {
            return ResponseEntity.badRequest().body("上传失败,文件为空");
        }

        try {
            // 保存目录
            String uploadDir = System.getProperty("user.dir") + "/uploads";
            File dir = new File(uploadDir);
            if (!dir.exists()) dir.mkdirs();

            // 保存文件
            String filePath = uploadDir + "/" + file.getOriginalFilename();
            file.transferTo(new File(filePath));

            return ResponseEntity.ok("上传成功,文件路径:" + filePath);
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.internalServerError().body("上传失败:" + e.getMessage());
        }
    }
}

✅ 六、运行项目

  1. 在 IDEA 或命令行执行:

    mvn spring-boot:run
    
  2. 打开浏览器,创建一个 HTML 页面测试:


    
    


✅ 七、上传结果

  • 成功上传后文件保存在:

    项目目录/uploads/文件名
    
  • 浏览器返回提示:

    上传成功,文件路径:...
    

运行效果:

springboot的后端处理HTML的页面请求_第1张图片

你可能感兴趣的:(springboot的后端处理HTML的页面请求)