将 MultiPart 文件从 Android 上传到服务器 (SpringMVC)

Upload MultiPart file from Android to server(SpringMVC)

如果,我使用 Postmam 文件上传没有问题。但是,当 anroid 尝试在服务器中上传文件时,方法会抛出 NPE,因为 MultipartFile file = null。

Android

RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"), file);

Call<MediaResponseModel> call = service.uploadImage(requestBody);

call.enqueue(new RetrofitCallback<>(callback));


@POST("/uploadImage")

Call<MediaResponseModel> uploadImage(@Part("file") RequestBody file);

服务器

@RequestMapping(value = "/uploadImage", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<?> imageUpload(@RequestHeader(value = "id") String sessionId,
                                      @RequestParam (value = "file")   MultipartFile file)

ApplicationContext

 <bean id="jsonConverter"
      class="org.springframework.http.converter.json.GsonHttpMessageConverter">
    <property name="supportedMediaTypes">
        <list>
            <value>application/json;charset=UTF-8</value>
        </list>
    </property>
</bean>

<mvc:annotation-driven >
<mvc:message-converters>
    <bean class="org.springframework.http.converter.json.GsonHttpMessageConverter"/>
</mvc:message-converters>
</mvc:annotation-driven>

在 android 上使用 HTTP 很难做到这一点,您可以使用一些第三方库。

  1. ion
  2. retrofit

两个都是很好的库,我都在我的项目中使用过。

您可以使用 Retrofit 网络库,它是最快的

支持multipart文件,实现非常简单

http://square.github.io/retrofit/