使用Spring MVC和Retrofit 2.0将文件上传到服务器时遇到问题

时间:2019-03-07 06:48:00

标签: java spring-mvc file-upload retrofit2

这是我的后端方法。

  @IsAdmin
@RequestMapping(value = "/student/upload/file/{operation}/{format}/", 
method = RequestMethod.POST)
 public ResponseEntity<?> handleStudentFile(@PathVariable String 
operation, @PathVariable String format, @RequestParam("file") 
  MultipartFile file) {
    return studentHandler.handleStudent(operation, format, file);
}

以下是我的android方法,

@Multipart
    @POST("admin/student/upload/file/{operation}/{format}/")
    Call<ServerResponse> uploadNew(@Path("operation") String 
 operation, @Path("format") String format, @PartMap Map<String, 
MultipartBody> map);

   Map<String, MultipartBody> map = new HashMap<>();
           File file = new File(filePath);
        MultipartBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM)
                .addFormDataPart("file", file.getName(),

RequestBody.create(MediaType.parse("application/vnd.ms-excel"), file))
//                    .addFormDataPart("some-field", "some-value")
                    .build();
            map.put("file\"; filename=\"" + file.getName() + "\"", 
requestBody);
            ApiCallService.action(getActivity(), map, 
ACTION_UPLOAD_EXCEL);

上述方法文件的内容不正确,

我已经尝试过这种方式,

  @Multipart
    @POST("admin/student/upload/file/{operation}/{format}/")
    public Call<ServerResponse> upload(@Path("operation") String 
operation, @Path("format") String format, @Part("file") RequestBody 
file);



 MultipartBody.Builder multiPartBody =new 
 MultipartBody.Builder().setType(MultipartBody.FORM)
                    .addFormDataPart("file", file.getName(),

 RequestBody.create(MediaType.parse("application/vnd.ms-excel"), 
 file));

             ApiCallService.action(getActivity(), 
  multiPartBody.build(), ACTION_UPLOAD_EXCEL2);

帮我,我在做什么错了,我被困住了。

我在后端遇到异常,

 org.apache.poi.openxml4j.exceptions.InvalidFormatException: Your 
  InputStream was neither an OLE2 stream, nor an OOXML stream

0 个答案:

没有答案