简体   繁体   English

当前请求不是多部分请求 Spring Boot 和 Postman (Uploading json file plus extra field)

[英]Current request is not a multipart request Spring Boot and Postman (Uploading json file plus extra field)

I'm getting this Current request is not a multipart request error when trying to upload a json file and an extra id or dto object for my request, since this is also required to populate my database.尝试为我的请求上传 json 文件和额外的 id 或 dto 对象时,我收到此Current request is not a multipart request错误,因为这也是填充我的数据库所必需的。

When I am sending only the json file, everything is being uploaded fine, but now I've added the id field to the related methods and Postman, I'm getting this message and struggling to debug and fix it, if I can get any help please.当我只发送 json 文件时,所有内容都可以正常上传,但是现在我已将 id 字段添加到相关方法和 Postman,我收到此消息并努力调试和修复它,如果我能得到的话请帮忙。

These are the pieces involved:这些是涉及的部分:

@Controller
@RequestMapping("/api/gatling-tool/json")
public class StatsJsonController {

@Autowired
StatsJsonService fileService;

@PostMapping(value = "/import")
public ResponseEntity<ResponseMessage> uploadFile(@RequestParam("file") MultipartFile file, @RequestBody CategoryQueryDto categoryQueryDto) {
    String message = "";

    UUID id = categoryQueryDto.getId();

    if (StatsJsonHelper.hasJsonFormat(file)) {
        try {
            fileService.save(file, id);

            message = "Uploaded the file successfully: " + file.getOriginalFilename();
            return ResponseEntity.status(HttpStatus.OK).body(new ResponseMessage(message));
        } catch (Exception e) {
            message = "Could not upload the file: " + file.getOriginalFilename() + "!";
            return ResponseEntity.status(HttpStatus.EXPECTATION_FAILED).body(new ResponseMessage(message));
        }
    }

    message = "Please upload a json file!";
    return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseMessage(message));
}

}




@Service
public class StatsJsonService {

@Autowired
StatsJsonRepository repository;

public void save(MultipartFile file, UUID id) {
    StatsEntity statsEntity = StatsJsonHelper.jsonToStats(file, id);
    repository.save(statsEntity);
}

}


public class StatsJsonHelper {

public static String TYPE = "application/json";

public static boolean hasJsonFormat(MultipartFile file) {

    if (!TYPE.equals(file.getContentType())) {
        return false;
    }

    return true;
}

public static StatsEntity jsonToStats(MultipartFile file, UUID id) {

    try {
        Gson gson = new Gson();

        File myFile = convertMultiPartToFile(file);

        BufferedReader br = new BufferedReader(new FileReader(myFile));

        Stats stats = gson.fromJson(br, Stats.class);
         StatsEntity statsEntity = new StatsEntity();
        
        statsEntity.setGroup1Count(stats.stats.group1.count);
        statsEntity.setGroup1Name(stats.stats.group1.name);
        statsEntity.setGroup1Percentage(stats.stats.group1.percentage);


        statsEntity.setId(id);

        return statsEntity;

    } catch (IOException e) {
        throw new RuntimeException("fail to parse json file: " + e.getMessage());
    }
}

在此处输入图片说明

在此处输入图片说明

在此处输入图片说明

Thank you very much.非常感谢。

https://github.com/francislainy/gatling_tool_backend/pull/3/files https://github.com/francislainy/gatling_tool_backend/pull/3/files

UPDATE更新

Added changes as per @dextertron's answers (getting a 415 unsupported media type error)根据@dextertron 的回答添加了更改(得到 415 unsupported media type 错误)

@PostMapping(value = "/import")
public ResponseEntity<ResponseMessage> uploadFile(@RequestParam("file") MultipartFile file, @RequestBody CategoryQueryDto categoryQueryDto) {

在此处输入图片说明

在此处输入图片说明

The same error persists even if I change this part from application/json to multiform/data as well.即使我将这部分从 application/json 更改为 multiform/data,同样的错误仍然存​​在。

public static String TYPE = "multiform/data";

I tried with couple of combinations in controller.我在控制器中尝试了几种组合。

The one Worked for me looks something like this.为我工作的那个看起来像这样。 Basically we will have to pass both arguments as @RequestParam .基本上我们必须将两个参数作为@RequestParam传递。

    @PostMapping("/import")
    public ResponseEntity<Object> uploadFile(@RequestParam("file") MultipartFile file, @RequestParam String id) {
        return null;
    }

I know you wanted to pass CategoryQueryDto as @RequestBody But it seems in multipart request @RequestParam and @RequestBody doesn't seem to work together.我知道您想将CategoryQueryDto作为@RequestBody传递但它似乎在多部分请求中@RequestParam@RequestBody似乎不能一起工作。

So you IMO you can do 2 things here :-所以你 IMO 你可以在这里做两件事:-

  1. Design the controller as above and just send the id as string in request and use that in fileService.save(file, id);如上所述设计控制器,并在请求中将id作为字符串发送并在fileService.save(file, id);使用它fileService.save(file, id); directly.直接地。 在此处输入图片说明

  2. If you still want to use CategoryQueryDto you can send this {"id":"adbshdb"} and then convert it to CategoryQueryDto using object mapper.如果您仍想使用CategoryQueryDto您可以发送此{"id":"adbshdb"} ,然后使用对象映射器将其转换为CategoryQueryDto

This is how your controller will look like -这就是您的控制器的外观 -

    @PostMapping("/import")
    public ResponseEntity<Object> uploadFile(@RequestParam("file") MultipartFile file, @RequestParam String categoryQueryDtoString) throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        CategoryQueryDto categoryQueryDto = objectMapper.readValue(categoryQueryDtoString, CategoryQueryDto.class);
// Do your file related stuff
        return ResponseEntity.ok().body(file.getOriginalFilename());
    }

And this is how you can send request using postman/ARC -这就是您可以使用邮递员/ARC发送请求的方式-

在此处输入图片说明

PS: Dont forget to set Content-Type header like so - PS:不要忘记像这样设置 Content-Type 标头 - 在此处输入图片说明

First, you need to set the Content-Type headers to be "multipart/form-data", then as the second parameter in form-data use "categoryQueryDto" as key and add json as value ({'id': 'whatever'}).首先,您需要将 Content-Type 标头设置为“multipart/form-data”,然后作为 form-data 中的第二个参数,使用“categoryQueryDto”作为键并添加 json 作为值 ({'id': 'whatever' })。

在此处输入图片说明

After that change annotation for parameters from @RequestPart/@RequestBody to @RequestParam in your controller.之后,将参数的注释从 @RequestPart/@RequestBody 更改为控制器中的 @RequestParam。

在此处输入图片说明

在此处输入图片说明

Posting another solution that I experimented with which was to append the id to the path for the call .发布我尝试过的另一个解决方案是将 id 附加到 call 的路径

@PostMapping(value = "/import/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<ResponseMessage> uploadFile(@RequestParam("file") MultipartFile file, @PathVariable(value = "id") UUID id) {
    String message = "";

    if (StatsJsonHelper.hasJsonFormat(file)) {
        try {
            fileService.save(file, id);

            message = "Uploaded the file successfully: " + file.getOriginalFilename();
            return ResponseEntity.status(HttpStatus.OK).body(new ResponseMessage(message));
        } catch (Exception e) {
            message = "Could not upload the file: " + file.getOriginalFilename() + "!";
            return ResponseEntity.status(HttpStatus.EXPECTATION_FAILED).body(new ResponseMessage(message));
        }
    }

    message = "Please upload a json file!";
    return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseMessage(message));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Spring-boot rest api当前请求不是邮递员的多部分请求 - Spring-boot rest api current request is not multipart request with postman Spring 引导多部分 REST 端点在从 Postman 调用时给出“当前请求不是多部分请求” - Spring Boot Multipart REST endpoint gives 'Current request is not a multipart request' when called from Postman 当前请求不是多部分请求:Spring boot - Current request is not a multipart request : Spring boot Spring 启动:当前请求不是多部分请求 - Spring boot: Current request is not a multipart request “当前请求不是多部分请求” angularjs和spring boot - “the current request is not a multipart request” angularjs and spring boot Spring Boot + Angular - MultipartException:当前请求不是多部分请求 - Spring Boot + Angular - MultipartException: Current request is not a multipart request org.springframework.web.multipart.MultipartException:当前请求不是多部分请求 spring boot - org.springframework.web.multipart.MultipartException: Current request is not a multipart request spring boot Spring / Jboss-当前请求不是多部分请求 - Spring/Jboss - Current Request is not multipart request 当前请求不是多部分请求 - Spring MVC - Current request is not a multipart request - Spring MVC 如何使用 Spring 引导传入请求将多部分文件映射到 DTO - How To Mapping Multipart file to DTO using Spring Boot for incoming request
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM