如何使用 swift 将动态生成的 Pdf 文件上传到 api

How to upload a dynamically generated Pdf file to api using swift

我正在做一个应用程序,它接受用户的输入并生成 PDF file.i"我正在尝试将生成的 pdf 文件上传到 api.but,我不知道该怎么做,我是 swift.can 的新手,请给我一个关于如何将文件上传到 api 的示例 提前致谢

首先,我建议您考虑使用 Alamofire if you don't want to get lost in the idiosyncrasies of composing network requests. If you do it yourself, it can get pretty hairy (see 作为示例,了解如何手动构建 multipart/formdata 请求。

其次,这个请求应该如何形成,完全取决于你如何设计API。但最简单的文件上传是支持 multipart/formdata 请求(例如在 PHP 中,使用 $_FILES 机制)。参见 http://php.net/manual/en/features.file-upload.php. Or see example here that not only uploads image file (which you can easily modify to accept PDFs), but constructs JSON response, too: 。

无论如何,如果您的服务器设计用于处理 multipart/formdata 请求,您可以使用 Alamofire 创建请求并解析响应,如 README 文件的 Uploading MultipartFormData 部分所示:

Alamofire.upload(
    .POST,
    "https://httpbin.org/post",
    multipartFormData: { multipartFormData in
        multipartFormData.appendBodyPart(fileURL: unicornImageURL, name: "unicorn")
        multipartFormData.appendBodyPart(fileURL: rainbowImageURL, name: "rainbow")
    },
    encodingCompletion: { encodingResult in
        switch encodingResult {
        case .Success(let upload, _, _):
            upload.responseJSON { response in
                debugPrint(response)
            }
        case .Failure(let encodingError):
            print(encodingError)
        }
    }
)