在Postman中使用图像文件发送JSON

问题描述 投票:0回答:1

我想在邮递员中发送带有图像的 JSON 文件,但收到以下错误:

“状态”:415,
“错误”:“不支持的媒体类型”,

专家控制器

package com.shayanr.HomeServiceSpring.controller;

import com.shayanr.HomeServiceSpring.entity.users.Expert;
import com.shayanr.HomeServiceSpring.service.ExpertService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

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

@RestController
@RequestMapping("/expert")
@RequiredArgsConstructor
public class ExpertController {
    private ExpertService expertService;

    @PostMapping("/register")
    public void register(@RequestBody Expert expert,
            @RequestParam("image") MultipartFile image) throws IOException {
        expertService.signUp(expert, image);
    }
}

专家服务

@Override
@Transactional
public Expert signUp(Expert expert, MultipartFile image) throws IOException {
    if (expert == null) {
        throw new NullPointerException("null expert");
    }
    if (!Validate.nameValidation(expert.getFirstName()) ||
            !Validate.nameValidation(expert.getLastName()) ||
            !Validate.emailValidation(expert.getEmail()) ||
            !Validate.passwordValidation(expert.getPassword())) {
        throw new PersistenceException("wrong validation");
    }
    String extension = FilenameUtils.getExtension(image.getName());
    if (extension.equalsIgnoreCase("video") || extension.equalsIgnoreCase("mp4")) {
        throw new PersistenceException("Invalid image format. Only image files are allowed.");
    }
    expert.setConfirmation(Confirmation.NEW);

    byte[] imageInbytes = image.getBytes();
    expert.setImage(imageInbytes);
    expertRepository.save(expert);
    return expert;

}

在邮递员中我的第一行是 json 和这个 json 文件

{
  "firstName": "Sasa",
  "lastName": "Weel",
  "email": "[email protected]",
  "password": "Sasasd1@",
  "signUpDate": "2024-01-31",
  "signUpTime": "10:00:00"
}

在第二行我设置图像问题出在哪里

java spring http postman
1个回答
0
投票

您的

@RequestParam("image") MultipartFile image
参数看起来正确。

所以接下来你应该做的就是确保告诉 Spring 你想要允许多部分文件。

这是一个示例

application.properties
配置:

spring.servlet.multipart.enabled=true

控制上传大小的其他配置设置:

# Adjust these file size restrictions and location as nessessary
spring.servlet.multipart.max-file-size=2MB
spring.servlet.multipart.max-request-size=10MB
spring.servlet.multipart.location=/temp

我怀疑

@RequestBody Expert expert
参数应该与此有关。

© www.soinside.com 2019 - 2024. All rights reserved.