首页 > 解决方案 > 使用javascript swagger客户端上传文件时遇到问题并做出反应

问题描述

我对 Swagger codegen 生成的源代码有疑问。我想上传一个带有反应的文件。为此,我创建了一个 Dropzone 并获取文件的路径。如果我按照文档中的方式使用生成的客户端,它将无法正常工作。不幸的是,该文件未发送。只有文件名。调试控制台也没有显示二进制数据已发送。

请求未正确执行。该文件将不会被上传。参数“file”只是文件名,而不是二进制数据。

Swagger-codegen 版本

openapi-generator-cli-3.3.4.jar

Swagger 声明文件内容

招摇.yaml:

  /orders/upload:
    post:
      operationId: "orderUploadPart"
      summary: "upload a textual or audio part of an order"
      tags:
        - "orders"
      description: "This funktion uploads a textual or audio part of an order to the sense.ai.tion cloud system. 
      The result is the resource identifier, that must be used in the order request."
      consumes:
        - multipart/form-data
      parameters:
        - in: "formData"
          name: "file"
          type: "file"
          required: true
          description: "the file to upload"
        - in: "formData"
          name: "media"
          type: "string"
          enum:
            - "text"
            - "wav"
            - "mp3"
          required: true
          description: "the media type of the the upload, can be ***text***, ***wav*** or ***mp3***"

代码:

var apiInstance = new SenseaitionApi.OrdersApi();
var file = "/path/to/file"; // File | the file to upload
var media = "media_example"; // String | the media type of the the upload, can be ***text***, ***wav*** or ***mp3***
var callback = function(error, data, response) {
  if (error) {
    console.error(error);
  } else {
    console.log('API called successfully. Returned data: ' + data);
  }
};
apiInstance.orderUploadPart(file, media, callback);

就像在:https ://github.com/swagger-api/swagger-codegen/blob/master/samples/client/petstore/javascript/docs/PetApi.md#uploadFile

屏幕截图 Chrome DevTools

用于生成的命令行

java -jar ${GOPATH}/bin/openapi-generator-cli.jar generate -i service_js_api.yaml -g javascript -o clients/javascript/senseaition-api-js -Dio.swagger.parser.util.RemoteUrl.trustAll=true

标签: javascriptreactjsswaggerswagger-codegenreact-dropzone

解决方案


我发现了错误。生成的 Javascript 代码的文档是错误的。对于上传文件(Javascript 对象),必须传递,而不是路径。

这一行是错误的:

var file = "/path/to/file"; // File | the file to upload 

推荐阅读