我是Spring boot和android开发的新手。我正在尝试设置和Android应用程序(使用retrofit和okhttp3),它将上传图像到我的服务器。
服务器代码:
@RestController
public class ImageController {
@RequestMapping(value = "/uploadImage", method =RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public String greeting(@RequestPart(value="desc") RequestBody desc, @RequestPart(value="img") MultipartBody.Part image) {
System.out.println("Works");
return "Works";
}
}
Android代码:
MultipartBody.Part fileToUpload = MultipartBody.Part.createFormData("file", imageFile.getName(), requestBody);
RequestBody name = RequestBody.create(MediaType.parse("text/plain"), imageFile.getName());
@Multipart
@POST("/uploadImage")
Observable<retrofit2.Response<String>> uploadPhoto(@Part("desc") RequestBody desc,@Part MultipartBody.Part image);
错误:
{“timestamp”:1519756785858,“status”:415,“error”:“Unsupported Media Type”,“exception”:“org.springframework.web.HttpMediaTypeNotSupportedException”,“message”:“Content type'text / plain; charset = utf-8'不支持“,”path“:”/ uploadImage“}
谁能告诉我我做错了什么????
编辑:
试试这个...
@RequestMapping(value = "/uploadImage", method = RequestMethod.POST)
public String greeting(@RequestParam("file") MultipartFile file) {
try {
byte[] bytes = file.getBytes();
//to save file, if it is your case
Path path = Paths.get("/" + file.getOriginalFilename());
Files.write(path, bytes);
} catch (IOException e) {
e.printStackTrace();
}
}
我不太了解您的Android代码,但我会尝试这样的事情:
HttpPost httpPost = new HttpPost("http://url");
httpPost.setEntity(new FileEntity(new File("filePath"), "application/octet-stream"));
HttpResponse response = httpClient.execute(httpPost);