【发布时间】:2021-01-17 09:00:12
【问题描述】:
我在尝试为我的请求上传 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 不支持的媒体类型错误)
@PostMapping(value = "/import")
public ResponseEntity<ResponseMessage> uploadFile(@RequestParam("file") MultipartFile file, @RequestBody CategoryQueryDto categoryQueryDto) {
即使我将这部分从 application/json 更改为 multiform/data,同样的错误仍然存在。
public static String TYPE = "multiform/data";
【问题讨论】:
标签: java spring-boot rest postman content-type