【问题标题】:Spring boot @restcontroller upload errorSpring boot @restcontroller 上传错误
【发布时间】:2018-08-07 12:48:50
【问题描述】:

我是 Spring Boot 和 Android 开发的新手。我正在尝试设置 android 应用程序(使用改造和 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";
    }
}

安卓代码:

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"}

谁能告诉我我做错了什么????

【问题讨论】:

  • 欢迎来到 Stackoverflow。下次请正确格式化您的代码,以便其他人更好地阅读。这一次我为你做到了。

标签: java android spring-boot retrofit2 okhttp3


【解决方案1】:

编辑:

试试这个...

@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);

【讨论】:

  • 但是我得到了错误 {"timestamp":1519844515434,"status":415,"error":"Unsupported Media Type","exception":"org.springframework.web.HttpMediaTypeNotSupportedException" ,"message":"不支持内容类型'multipart/form-data;boundary=ad983eba-75d8-49cd-bbdc-e48f1ef44814'","path":"/uploadImage"}
  • @bdeane 我已经编辑了答案。检查它是否对您有帮助。
猜你喜欢
  • 2016-09-16
  • 2023-01-13
  • 1970-01-01
  • 2019-04-26
  • 1970-01-01
  • 2019-06-25
  • 1970-01-01
  • 2014-12-15
  • 2016-08-11
相关资源
最近更新 更多