当前请求不是多部分请求Spring Boot和Postman(正在上传json文件以及额外的字段) [英] Current request is not a multipart request Spring Boot and Postman (Uploading json file plus extra field)

查看:201
本文介绍了当前请求不是多部分请求Spring Boot和Postman(正在上传json文件以及额外的字段)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试为我的请求上载json文件和额外的id或dto对象时,我收到此当前请求不是多部分请求错误,因为这也是填充我的数据库所必需的

当我仅发送json文件时,所有内容都可以正常上传,但是现在我将id字段添加到相关方法和Postman中,我收到此消息并努力调试和修复它,如果我可以得到任何帮助.

这些是涉及的部分:

  @Controller@RequestMapping("/api/gatling-tool/json")公共类StatsJsonController {@AutowiredStatsJsonService fileService;@PostMapping(value ="/import")公共ResponseEntity< ResponseMessage>uploadFile(@RequestParam("file"))MultipartFile文件,@ RequestBody CategoryQueryDto categoryQueryDto){字符串消息=";UUID id = categoryQueryDto.getId();如果(StatsJsonHelper.hasJsonFormat(file)){尝试 {fileService.save(file,id);message =成功上传文件:"+ file.getOriginalFilename();返回ResponseEntity.status(HttpStatus.OK).body(new ResponseMessage(message));} catch(Exception e){message =无法上传文件:"+ file.getOriginalFilename()+!";返回ResponseEntity.status(HttpStatus.EXPECTATION_FAILED).body(new ResponseMessage(message));}}message =请上传一个json文件!";返回ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseMessage(message));}}@服务公共类StatsJsonService {@AutowiredStatsJsonRepository存储库;公共无效的保存(MultipartFile文件,UUID ID){StatsEntity statsEntity = StatsJsonHelper.jsonToStats(file,id);repository.save(statsEntity);}}公共类StatsJsonHelper {public static String TYPE ="application/json";公共静态布尔hasJsonFormat(MultipartFile file){如果(!TYPE.equals(file.getContentType())){返回false;}返回true;}公共静态StatsEntity jsonToStats(MultipartFile文件,UUID ID){尝试 {Gson gson =新的Gson();文件myFile = convertMultiPartToFile(file);BufferedReader br =新的BufferedReader(新的FileReader(myFile));统计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);返回statsEntity;} catch(IOException e){抛出新的RuntimeException("无法解析json文件:" + e.getMessage());}} 

非常感谢您.

即使我也将这一部分从application/json更改为multiform/data,同样的错误仍然存​​在.

 公共静态字符串TYPE ="multiform/data"; 

解决方案

我在控制器中尝试了几种组合.

为我工作的那个人看起来像这样.基本上,我们必须将两个参数都作为 @RequestParam 传递.

  @PostMapping("/import")公共ResponseEntity< Object>uploadFile(@RequestParam("file"))MultipartFile文件,@ RequestParam字符串ID){返回null;} 

我知道您想将 CategoryQueryDto 作为 @RequestBody 传递,但似乎在多部分请求中 @RequestParam @RequestBody 似乎不能一起工作.

因此,您在IMO可以在这里做两件事:-

  1. 按上述方法设计控制器,然后将 id 作为字符串发送到请求中,然后直接在 fileService.save(file,id); 中使用它.

  2. 如果您仍想使用 CategoryQueryDto ,则可以发送此 {"id":"adbshdb"} ,然后将其转换为使用对象映射器进行CategoryQueryDto .

这就是您的控制器的外观-

  @PostMapping("/import")公共ResponseEntity< Object>uploadFile(@RequestParam("file")MultipartFile文件,@ RequestParam字符串categoryQueryDtoString)引发JsonProcessingException {ObjectMapper objectMapper = new ObjectMapper();CategoryQueryDto categoryQueryDto = objectMapper.readValue(categoryQueryDtoString,CategoryQueryDto.class);//做文件相关的事情返回ResponseEntity.ok().body(file.getOriginalFilename());} 

这是您可以使用邮递员/ARC发送请求的方式-

PS:别忘了像这样设置Content-Type标头-

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.

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.

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

UPDATE

Added changes as per @dextertron's answers (getting a 415 unsupported media type error)

@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.

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.

    @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.

So you IMO you can do 2 things here :-

  1. Design the controller as above and just send the id as string in request and use that in 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.

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 -

PS: Dont forget to set Content-Type header like so -

这篇关于当前请求不是多部分请求Spring Boot和Postman(正在上传json文件以及额外的字段)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆