有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java使用改型将文件作为multipart/formdata上传会产生400个错误代码

尝试将图像作为多部分/表单数据上传,如下所示就是表单数据的形成

这就是spring boot方法的参数。此方法位于一个单独的spring boot应用程序中,该应用程序将文件保存到数据库中

public String uploadFile(@RequestParam("file") MultipartFile file,@RequestParam("desc") String desc,@RequestParam("uploadId") String uploadId ) {...}

我得到了错误代码400(错误请求),errorBody给出了空字符串。我无法理解我做错了什么。 下面的代码用于形成表单数据请求

try {
            RequestBody reqFile = RequestBody.create(MediaType.parse("image/jpeg"), file);
            MultipartBody.Part body = MultipartBody.Part.createFormData("file", file.getName(), reqFile);

            String descStr = file.getName();
            RequestBody desc = RequestBody.create(MediaType.parse("text/plain"), descStr);

            String uploadIdStr = receiptId;
            RequestBody uploadId = RequestBody.create(MediaType.parse("text/plain"), uploadIdStr);

            imgRequest = RetrofitHelper.uploadImage(ApplicationConstants.BEARER + " " + StringBox.getInstance(mActivity).getStringPreference(ApplicationConstants.ACCESS_TOKEN), body, desc, uploadId);
        } catch (IOException e) {
            Log.e(tag, e.getMessage());
        }


        imgRequest.enqueue(new Callback<ResponseBody>() {...}

改装API的配置如下所示

@Multipart
    @POST("/upload")
    Call<ResponseBody> uploadImage(@Header("Content-Type") String type,
                                   @Header("Authorization") String authorization,
                                   @Part MultipartBody.Part file,
                                   @Part("desc") RequestBody req,
                                   @Part("uploadId") RequestBody uploadId);
public static Call<ResponseBody> uploadImage(String accessToken, MultipartBody.Part body, RequestBody desc, RequestBody req) {
        RetrofitAPI mApi = RetrofitClient.getInstance().create(RetrofitAPI.class);

        Call<ResponseBody> uploadImage = mApi.uploadImage("multipart/form-data; boundary=" + System.currentTimeMillis(), accessToken, body, desc, req);

        return uploadImage;
    }

下面是响应标题

Date: Wed, 23 Sep 2020 07:13:25 GMT
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
Transfer-Encoding: chunked
Connection: close

共 (1) 个答案

  1. # 1 楼答案

    我在四处寻找我面临的一个相关问题,以下是我的发现。 enter image description here


    1. 然后上传部分图片

      @Multipart
      @POST("api/uploadpic")
      fun submitDP(@Part body: MultipartBody.Part): Call<UploadImageResponse>
      

    1. 避免手动添加标题,因为@Multipart注释会处理它。当我需要添加授权头时,我更喜欢拦截器

              class OAuthInterceptor(private val tokenType: String, private val 
               accessToken: 
               String) :
               Interceptor {
               override fun intercept(chain: Interceptor.Chain): okhttp3.Response {
               var request = chain.request()
               //do not pass content length to GET requests
               if(!request.method().equals("GET"))
               request = request.newBuilder()
              .header("Authorization", "$tokenType $accessToken")
              .header("Content-Length", request.body()?.contentLength().toString())
              .header("Host", "your.domain.com") //if this is not added then add 
               HostnameVerifier to interceptor
              .header("Accept", "application/json")
              .build()
          else
              request = request.newBuilder()
                  .header("Authorization", "$tokenType $accessToken")
                  .header("Host", "your.domain.com")
                  .header("Accept", "application/json")
                  .build()
          return chain.proceed(request)
      }
      

      }


    1. 然后使用表单数据作为内容创建零件

      val requestFile: RequestBody = RequestBody.create(MediaType.parse("image/jpg"), 
      bytes)
      val body: MultipartBody.Part = MultipartBody.Part.createFormData("your_key", 
      "image", requestFile)