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

Angular 5 + Spring Boot图片上传报错求助:Current request is not a multipart request

解决Angular向Spring Boot上传图片时的MultipartException问题

这个错误很常见,本质是Spring Boot没识别到你的请求是multipart/form-data类型,大概率是前端请求格式不对,或者后端代码/配置有疏漏。我给你分前后端一步步梳理解决方法,都是新手友好的:

一、后端(Spring Boot)修复步骤

1. 确保依赖正确

你用的是Spring 4.3.13(对应Spring Boot 1.5.x版本),只要你的pom.xml里包含了spring-boot-starter-web依赖,就已经自带multipart支持了,不用额外加依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

2. 修正RestController代码

你的控制器方法需要明确指定请求方法为POST,并且消费multipart/form-data类型,同时参数要用@RequestParam绑定MultipartFile对象。示例代码如下:

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
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;

// 跨域配置:如果Angular和Spring Boot端口不同,加上这个注解(替换成你的Angular端口,比如4200)
@CrossOrigin(origins = "http://localhost:4200")
@RestController
public class UserController {

    // 明确指定consumes类型为multipart/form-data
    @PostMapping(value = "/add-user", consumes = "multipart/form-data")
    public ResponseEntity<ResponseMessage> addUser(
            @RequestParam("profileImage") MultipartFile profileImage, // 这里的参数名要和前端FormData的key一致
            @RequestParam("username") String username) { // 示例:如果需要传其他用户信息

        // 先检查文件是否为空
        if (profileImage.isEmpty()) {
            return new ResponseEntity<>(new ResponseMessage("上传的图片不能为空"), HttpStatus.BAD_REQUEST);
        }

        // 这里写你的文件处理逻辑:比如保存到本地、上传到OSS等
        // 示例:获取文件流 profileImage.getInputStream()
        // 示例:获取文件名 profileImage.getOriginalFilename()

        return new ResponseEntity<>(new ResponseMessage("图片上传成功"), HttpStatus.OK);
    }
}

3. 配置文件大小限制(可选)

如果上传的图片较大,需要在application.properties里添加配置,避免超出默认限制:

# 单个文件最大大小(按需调整)
spring.http.multipart.max-file-size=10MB
# 整个请求的最大大小
spring.http.multipart.max-request-size=10MB

二、前端(Angular)修复步骤

前端核心是正确构建FormData对象,并且不要手动设置请求头(Angular会自动处理)。

1. 组件逻辑代码

import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-user-upload',
  templateUrl: './user-upload.component.html'
})
export class UserUploadComponent {
  selectedImage: File | null = null;
  userName: string = '';

  constructor(private http: HttpClient) {}

  // 监听文件选择事件
  onImageSelected(event: Event): void {
    const input = event.target as HTMLInputElement;
    if (input.files && input.files.length > 0) {
      this.selectedImage = input.files[0];
    }
  }

  // 执行上传操作
  uploadUser(): void {
    if (!this.selectedImage || !this.userName) {
      alert('请选择图片并填写用户名');
      return;
    }

    // 构建FormData,key要和后端@RequestParam的参数名完全一致
    const formData = new FormData();
    formData.append('profileImage', this.selectedImage); // 和后端的@RequestParam("profileImage")对应
    formData.append('username', this.userName); // 和后端的@RequestParam("username")对应

    // 发送POST请求,不用手动设置Content-Type!
    this.http.post<ResponseMessage>('http://localhost:8080/add-user', formData)
      .subscribe({
        next: (res) => {
          console.log('上传成功:', res);
          alert('用户信息和图片上传成功');
        },
        error: (err) => {
          console.error('上传失败:', err);
          alert('上传失败,请检查控制台日志');
        }
      });
  }
}

2. 组件模板代码(HTML)

<div class="upload-container">
  <input type="file" accept="image/*" (change)="onImageSelected($event)" />
  <input type="text" [(ngModel)]="userName" placeholder="请输入用户名" />
  <button (click)="uploadUser()">提交用户信息</button>
</div>

3. 关键注意事项

  • 不要手动设置Content-Type:如果手动设置headers: {'Content-Type': 'multipart/form-data'},会丢失自动生成的boundary参数,导致后端无法识别multipart请求。
  • 参数名必须完全匹配:前端formData.append('xxx', ...)的xxx要和后端@RequestParam("xxx")的xxx完全一致,大小写敏感。

三、常见排查点

  1. 检查浏览器开发者工具的Network标签,查看请求的Content-Type是否为multipart/form-data; boundary=xxxxxx,如果不是,说明前端请求构建错误。
  2. 确认请求方法是POST,GET请求无法传输multipart数据。
  3. 检查跨域问题:如果Angular和Spring Boot端口不同,必须在后端添加@CrossOrigin注解或者全局跨域配置。

内容的提问来源于stack exchange,提问作者Arul Rozario

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:22:18