gpt4 book ai didi

java - 尝试在 Spring Rest api 中上传文件时收到 415 不支持的媒体类型

转载 作者:行者123 更新时间:2023-11-30 03:14:09 26 4
gpt4 key购买 nike

我已经制作了一项接受文件并尝试存储在本地文件系统中的服务但是当我尝试使用 html 文件向此服务发出请求时

我已经用谷歌搜索了这个错误,但很多人告诉我,该错误是由于服务器配置错误造成的,所以请告诉我服务器上的任何更改

我的服务器java代码:

@RequestMapping(value = "/upload",headers = "Content-Type=multipart/form-data", method = RequestMethod.POST)
@ResponseBody
public String upload(@RequestBody MultipartFile file)
{
name = "/path";

if (!file.isEmpty()) {
try {
byte[] bytes = file.getBytes();
BufferedOutputStream stream =
new BufferedOutputStream(new FileOutputStream(new File(name)));
stream.write(bytes);
stream.close();
System.out.println(file);
//s return "You successfully uploaded " + name + "!";
} catch (Exception e) {
return "You failed to upload " + name + " => " + e.getMessage();
}
} else {
return "You failed to upload " + name + " because the file was empty.";
}
}
return "";
}

我的html文件:

<html>
<body>
<form method="POST" enctype="multipart/form-data"
action="http://localhost:8080/upload">
File to upload: <input type="file" class = "file" name="file"><br /> <br /> <input type="submit"
value="Upload"> Press here to upload the file!
</form>
</body>
</html>

最佳答案

我认为@RequestBody对于文件上传是错误的。我是这样做的:

UserController.java:

@RequestMapping(value = "/upload/avatar/{userId}", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<?> uploadAvatar(@PathVariable("userId") Long userId, MultipartHttpServletRequest request) throws IOException {
String fileName = request.getFileNames().next();
userService.addAvatar(userId, fileName, request.getFile(fileName));
return new ResponseEntity<>(HttpStatus.OK);
}

UserService.java:

@Transactional
public void addAvatar(final Long userId, final String fileName, final MultipartFile avatar) throws IOException {
byte[] bytes = IOUtils.toByteArray(avatar.getInputStream());
long size = avatar.getSize();
File file = new File(bytes, size, avatar.getContentType(), fileName);

final User user = userRepository.findOne(agencyId);
user.setAvatar(file);
userRepository.save(user);
}

文件是我保存上传文件信息的实体

关于java - 尝试在 Spring Rest api 中上传文件时收到 415 不支持的媒体类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33014684/

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