从Android上传多部分文件到服务器(SpringMVC)

3

如果我使用Postman文件上传没有问题。但是,当安卓尝试上传文件到服务器时,该方法会抛出NPE异常,因为MultipartFile文件为空。

安卓

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>
2个回答

1

1

使用HTTP在Android上进行操作比较困难,但是你可以使用一些第三方库来实现。

  1. ion
  2. retrofit

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


1
我不知道为什么这个答案被接受了,它根本没有回答问题。 - forresthopkinsa

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接