如何在Alamofire中将pdf文件作为多部分表格数据上传?

时间:2019-10-11 07:37:50

标签: swift alamofire

我必须将pdf文件作为多部分表格数据上传。
我读了Alamofire/Usage.md(Uploading Data to a Server)

所以我写下面的代码。

extension ViewController: UIDocumentPickerDelegate {

    func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
        guard let url = urls.first else { return }
        print(url) // file:///private/var/mobile/Containers/Data/Application/69C5B45A-AA29-46D2-909C-2A1A5A68C10F/tmp/com.test.test-Inbox/D5100_EN.pdf
        do {
            let data = try Data(contentsOf: url)
            print(data) // 10899227 bytes
            AF.upload(multipartFormData: { multipartFormData in
                multipartFormData.append(data, withName: "pdf")
            }, to: "https://myurl.com")
                .responseJSON { response in
                    debugPrint(response) // message = "Required request part 'file' is not present"
            }
        } catch {
            print(error)
        }
    }

}

但它已提起诉讼。
如何在alamofire中将pdf文件作为多部分表单数据上传?

2 个答案:

答案 0 :(得分:2)

您需要指定mimeType

multipartFormData.append(pdfData, withName: "pdfDocuments", fileName: "pdf", mimeType:"application/pdf")

已更新

根据错误,您必须了解服务器正在使用名称为“ file”的pdf

尝试一下:

 multipartFormData.append(pdfData, withName: "file", fileName: "file", mimeType:"application/pdf")

答案 1 :(得分:0)

您可能需要指定MimeType。尝试将您的请求更新为

AF.upload(multipartFormData: { multipartFormData in
    multipartFormData.append(data, withName: "name", fileName: "fileName", mimeType: "application/pdf")
}, to: "https://myurl.com")
    .responseJSON { response in
        debugPrint(response) // message = "Required request part 'file' is not present"
}