gpt4 book ai didi

java - 为 Spring MVC Post 请求返回 JSON 响应

转载 作者:可可西里 更新时间:2023-11-01 16:30:39 26 4
gpt4 key购买 nike

我有下面的 Controller 方法,它正在将文件上传到我的服务器。我想为 Plupload 的状态返回 JSON。但是,响应似乎作为调度而不是 json @ResponseBody 发回。有什么想法吗?

    private static final String RESP_SUCCESS = "{\"jsonrpc\" : \"2.0\", \"result\" : \"success\", \"id\" : \"id\"}";
private static final String RESP_ERROR = "{\"jsonrpc\" : \"2.0\", \"error\" : {\"code\": 101, \"message\": \"Failed to upload file.\"}, \"id\" : \"id\"}";

@RequestMapping(method = RequestMethod.POST)
public String uploadItem(@RequestBody MultipartFile file,
@RequestParam String name,
@RequestParam(required = false, defaultValue = "-1") int chunks,
@RequestParam(required = false, defaultValue = "-1") int chunk) {
Media media = new Media();
try {
Path path = Paths.get("/Users/username/Desktop/Test", file.getOriginalFilename());
media.setContentType(file.getContentType());
media.setFileName(file.getOriginalFilename());
media.setFileSize(file.getSize());
media.setFilePath(path.toString());
if (media.getContentType().contains("image")) {
Image image = new Image();
image.setImagePath(path.toString());
imageDao.save(image);
}
byte[] bytes = file.getBytes();
Files.write(path, bytes, StandardOpenOption.CREATE);
mediaDao.save(media);
return RESP_SUCCESS;
} catch (IOException e) {
e.printStackTrace();

}
return RESP_ERROR;
}
}

抛出以下错误:

WARN - No mapping found for HTTP request with URI [/{"jsonrpc" : "2.0", "result" : "success", "id" : "id"}] in DispatcherServlet with name 'cr'

最佳答案

我认为你的方法应该用@ResponseBody 注释。

@RequestMapping(method = RequestMethod.POST)
@ResponseBody
public String uploadItem(@RequestBody MultipartFile file,
@RequestParam String name,
@RequestParam(required = false, defaultValue = "-1") int chunks,
@RequestParam(required = false, defaultValue = "-1")

这是 Spring 检查 Json 转换的方式:

  • Jackson 库存在于项目类路径中
  • 启用了 mvc:annotation-driven
  • 用@ResponseBody注解的返回方法

Spring 会自动处理 JSON 转换。

关于java - 为 Spring MVC Post 请求返回 JSON 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16888628/

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