【问题标题】:Post call for file upload not working as expected using java使用java发布文件上传调用无法按预期工作
【发布时间】:2021-07-02 07:22:07
【问题描述】:

使用java进行文件上传的后调用无法按预期工作。我需要使用rest调用上传文件..文件格式正确,并且在邮递员和ui端也可以正常工作,但在java中它给出“不正确的文件格式“因为文件似乎没有上传。我是否缺少任何标题或任何内容。

File file = new File("/Users/surya/Downloads/2021-06-16.xlsx");
        
          Response response = RestAssured
                    .given()
                    .multiPart("file", file, "multipart/form-data")                
                    .post("http://myuploadsite.com/upload/feedfile");         
            System.out.println(response.asString());

我的邮递员 curl 请求

curl --location --request POST 'http://myuploadsite.com/upload/feedfile' \
--header 'Content-Type: multipart/form-data; boundary=jena' \
--header 'Host;' \
--form 'file=@"/Users/surya/Downloads/2021-06-16.xlsx"'

【问题讨论】:

  • inside body 写什么??
  • 没有。它不工作..得到相同的 eroor..我可以直接调用邮递员 curl 命令

标签: java selenium rest postman rest-assured


【解决方案1】:

您使用的方法是:

RequestSpecification multiPart(String controlName, File file, String mimeType);

您需要为要上传的文件定义mimeType,在本例中为application/vnd.openxmlformats-officedocument.spreadsheetml.sheetapplication/vnd.ms-excel。我不太确定是哪一个。

或者留空使用重载方法:

RequestSpecification multiPart(String controlName, File file);

代码是:

File file = new File("/Users/surya/Downloads/2021-06-16.xlsx");
        
Response response = RestAssured
      .given()
      .multiPart("file", file, "application/vnd.ms-excel")                
      .post("http://myuploadsite.com/upload/feedfile");         
System.out.println(response.asString());

当您使用multipart时,Rest-Assured 会自动定义Content-Type: multipart/form-data

https://github.com/rest-assured/rest-assured/wiki/Usage#multi-part-form-data

【讨论】:

    猜你喜欢
    • 2013-08-18
    • 2020-05-02
    • 1970-01-01
    • 2023-03-24
    • 2011-05-12
    • 2023-04-10
    • 2020-04-16
    • 2020-08-04
    • 1970-01-01
    相关资源
    最近更新 更多