簡體   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)

嘗試為我的請求上傳 json 文件和額外的 id 或 dto 對象時,我收到此Current request is not a multipart request錯誤,因為這也是填充我的數據庫所必需的。

當我只發送 json 文件時,所有內容都可以正常上傳,但是現在我已將 id 字段添加到相關方法和 Postman,我收到此消息並努力調試和修復它,如果我能得到的話請幫忙。

這些是涉及的部分:

@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());
    }
}

在此處輸入圖片說明

在此處輸入圖片說明

在此處輸入圖片說明

非常感謝。

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

更新

根據@dextertron 的回答添加了更改(得到 415 unsupported media type 錯誤)

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

在此處輸入圖片說明

在此處輸入圖片說明

即使我將這部分從 application/json 更改為 multiform/data,同樣的錯誤仍然存​​在。

public static String TYPE = "multiform/data";

我在控制器中嘗試了幾種組合。

為我工作的那個看起來像這樣。 基本上我們必須將兩個參數作為@RequestParam傳遞。

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

我知道您想將CategoryQueryDto作為@RequestBody傳遞但它似乎在多部分請求中@RequestParam@RequestBody似乎不能一起工作。

所以你 IMO 你可以在這里做兩件事:-

  1. 如上所述設計控制器,並在請求中將id作為字符串發送並在fileService.save(file, id);使用它fileService.save(file, id); 直接地。 在此處輸入圖片說明

  2. 如果您仍想使用CategoryQueryDto您可以發送此{"id":"adbshdb"} ,然后使用對象映射器將其轉換為CategoryQueryDto

這就是您的控制器的外觀 -

    @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());
    }

這就是您可以使用郵遞員/ARC發送請求的方式-

在此處輸入圖片說明

PS:不要忘記像這樣設置 Content-Type 標頭 - 在此處輸入圖片說明

首先,您需要將 Content-Type 標頭設置為“multipart/form-data”,然后作為 form-data 中的第二個參數,使用“categoryQueryDto”作為鍵並添加 json 作為值 ({'id': 'whatever' })。

在此處輸入圖片說明

之后,將參數的注釋從 @RequestPart/@RequestBody 更改為控制器中的 @RequestParam。

在此處輸入圖片說明

在此處輸入圖片說明

發布我嘗試過的另一個解決方案是將 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM