gpt4 book ai didi

spring - 使用 Spring 的 REST 多部分混合请求(文件+json)

转载 作者:IT老高 更新时间:2023-10-28 13:50:04 26 4
gpt4 key购买 nike

我需要将一个文件与一个 json 一起发送到我的 Spring Controller。我有以下 Controller 类:

@Controller
@RequestMapping("/perform")
public class PerformController {

...

@RequestMapping(path = "gopdf", method = RequestMethod.POST, consumes = { "multipart/mixed" })
@ResponseStatus(HttpStatus.CREATED)
public void handleFileUpload(@RequestPart("file") MultipartFile file, @RequestPart("map") String map, HttpServletResponse response) throws Exception {
...
}

}

但是当我使用以下命令在我的服务器上 curl 时:

 curl -H "Content-Type: multipart/form-data" -F "map=@map.json; type=application/json" -F "content=@SMP.docx" -X POST localhost:9000/perform/gopdf-i -v

我得到 415 不受支持的媒体类型!

有什么线索吗?

最佳答案

其他答案中的消耗对我来说并没有做废话。关键是将我想要支持的特定 multipart/* 类型添加到 RequestMapping 中的某些 header 键上。这真的很难弄清楚,主要是猜测工作并盯着 Spring 源代码。我对 Spring 对此的支持有点不知所措,但我已经设法让它在我们的 Spring Boot 应用程序中工作,但仅限于 Tomcat?!?当您将引导应用程序配置为使用 Jetty 时,称为 MultipartResolver 的东西会阻塞……所以长 Jetty。但我离题了...

在我的 Controller 中,我设置了 multipart/mixed 或 multipart/form-data 之类的...

@RequestMapping(value = "/user/{userId}/scouting_activities", method = RequestMethod.POST,
headers = {"content-type=multipart/mixed","content-type=multipart/form-data"})
public ResponseEntity<String> POST_v1_scouting_activities(
@RequestHeader HttpHeaders headers,
@PathVariable String userId,
@RequestPart(value = "image", required = false) MultipartFile image,
@RequestPart(value = "scouting_activity", required = true) String scouting_activity_json) {
LOG.info("POST_v1_scouting_activities: headers.getContentType(): {}", headers.getContentType());
LOG.info("POST_v1_scouting_activities: userId: {}", userId);
LOG.info("POST_v1_scouting_activities: image.originalFilename: {}, image: {}",
(image!=null) ? image.getOriginalFilename() : null, image);
LOG.info("POST_v1_scouting_activities: scouting_activity_json.getType().getName(): {}, scouting_activity: {}",
scouting_activity_json.getClass().getName(), scouting_activity_json);
return new ResponseEntity<String>("POST_v1_scouting_activities\n", HttpStatus.OK);
}

标题让它能够唯一地识别它愿意尝试的多部分内容类型。这让卷发像......

curl -i -X POST 'http://localhost:8080/robert/v1/140218/scouting_activities' \
-H 'Content-type:multipart/mixed' \
-F 'image=@Smile_128x128.png;type=image/png' \
-F 'scouting_activity={
"field": 14006513,
"longitude": -93.2038253,
"latitude": 38.5203231,
"note": "This is the center of Dino Head.",
"scouting_date": "2017-01-19T22:56:04.836Z"
};type=application/json'

...或...

curl -i -X POST 'http://localhost:8080/robert/v1/140218/scouting_activities' \
-H 'Content-type:multipart/form-data' \
-F 'image=@Smile_128x128.png;type=image/png' \
-F 'scouting_activity=@scoutingFrackingCurl.json;type=application/json'

工作。

关于spring - 使用 Spring 的 REST 多部分混合请求(文件+json),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38207049/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com