Alamofire 多部分/表单数据上传请求中仅不发送图像
Posted
技术标签:
【中文标题】Alamofire 多部分/表单数据上传请求中仅不发送图像【英文标题】:Only image isn't sent in Alamofire multipart/form-data upload request 【发布时间】:2017-12-15 13:58:44 【问题描述】:我有以下 Alamofire 请求,将一个简单的用户上传到服务器,其中包含电子邮件、姓名等数据,最后是头像图像。
Alamofire.upload(
multipartFormData: multipartFormData in
multipartFormData.append(self.selectedEmail.data(using: .utf8)!, withName: "email")
multipartFormData.append( self.selectedFirstName.data(using: .utf8)!, withName: "first_name")
multipartFormData.append(self.selectedLastName.data(using: .utf8)!, withName: "last_name")
if self.selectedGender == "Male"
multipartFormData.append("0".data(using: .utf8)!, withName: "gender")
else
multipartFormData.append("1".data(using: .utf8)!, withName: "gender")
let userId = String(describing: self.matchmakerModels?.filter( m in m.email == self.selectedMatchmakerEmail)[0].id)
multipartFormData.append(userId.data(using: .utf8)!, withName: "user_id")
if let data = UIImageJPEGRepresentation(self.selectedImage, 1)
multipartFormData.append(data, withName: "avatar", fileName: "avatar.jpeg", mimeType: "image/jpeg")
,
to: Constants.BASE_URL + Constants.API_VERSION + "single",
method: .post,
headers: ["Authorization": "Bearer \(oauthKey)", "Accept": "application/json"],
encodingCompletion: encodingResult in
switch encodingResult
case .success(request: let upload, _, _):
print("===========CURL REQUEST===========")
debugPrint(upload)
upload.responseJSON response in
print("===========RESPONSE=============")
debugPrint(response)
print("created single")
self.addSingleBtn.isEnabled = true
case .failure(let encodingError):
do
print(encodingError)
print("failed to add single")
)
由于某种原因,代码不能像我预期的那样工作。字符串字段正确传递到后端,但图像不是。我无法访问后端,但我知道它可以与邮递员请求一起正常工作。
邮递员请求的Curl如下所示。
curl -X POST \
http://some.net/url/to/post/the/data/model \
-H 'accept: application/json' \
-H 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6IjZjNjc0ODM1MDMzNGI1M2UyMmM0YTAyYmIxNGYwYTZlNWIxMWQ5OTE5YzVkYTQ4NTZkMDQ5YzU3MGJhYjVkNDliZjY4MGIzMGNmMjgyNmQxIn0.eyJhdWQiOiIyIiwianRpIjoiNmM2NzQ4MzUwMzM0YjUzZTIyYzRhMDJiYjE0ZjBhNmU1YjExZDk5MTljNWRhNDg1NmQwNDljNTcwYmFiNWQ0OWJmNjgwYjMwY2YyODI2ZDEiLCJpYXQiOjE1MTAwNTA3MDYsIm5iZiI6MTUxMDA1MDcwNiwiZXhwIjoxNTQxNTg2NzA2LCJzdWIiOiIxIiwic2NvcGVzIjpbXX0.k1fFhAX_JU49aqrzXZ80dL1N8LtQJMhmmfSmocwSFY7-U03S70UlCh7Ig8od9VXvOCbr95Ld-crjBOYRxOQON5aZM8gDydapKz37Ln4RhQF4GI17GOYOwkADccpdjwZQSFZzbkSMTaAWKpeYGFrPBego4DTcYPpKA08ylXEhuPgq5Dq9nK6MSOOUI9rJtiqj8dHkyWsIvuGb9y43_Qr4RSwD6VDIsfCabuqSmWHROvJXEwl-3Rpwi6rLQTPg5Lz0mEHTSMuZvpVTVLo0HOplMgO3OZUJ8GB7Km1zgUR7c8GNnveU-_BpTnsgnFOcFdLlXuki31pK-hjSJnww4vBcRDHLqw2DbqdlOmYn5Pamgq__ooIsC1nkk3j3njj6W8EGXLM_oUjXOlY5BQlV_y7F3ZzBZ7PVLV2A_apP5ufQWM-aLX5LyuKc9gyyY6eb19nRbI2ucDw_kLmO-afEpoK6sc-ZDByff_vTZjT9p1qam4WBvAcpefPJdw83yYjud89eYC82SdIRCu9rCsrXHDe3imgiX8JG1AyVxaaM4Iq-PL3DrUJle5eqY4UXYXxhWGn2aycamrXFAbQ8wU83PSJ34cqU9agrmPnYoP78tumH_q_IAN9A_owYaMKW4-v-LEPhUPIj33pet026y3Eb8C0rNp15mkwmt-wTP0IRBeuAN0M' \
-H 'cache-control: no-cache' \
-H 'content-type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW' \
-H 'postman-token: e66477f1-01c3-26cc-b054-09780aab9b11' \
-F email=foo@boo.com \
-F first_name=Foo \
-F last_name=Boo \
-F gender=1 \
-F user_id=1 \
-F 'avatar=@[object Object]'
谁能告诉我这两个请求有什么不同?
编辑。这些是debugPrint(upload)
和debugPring(response)
打印的请求和响应的调试打印输出
===========CURL REQUEST===========
$ curl -v \
-X POST \
-H "Content-Type: multipart/form-data; boundary=alamofire.boundary.b2cda80a0a64ceb1" \
-H "Accept-Encoding: gzip;q=1.0, compress;q=0.5" \
-H "Accept-Language: pl-PL;q=1.0" \
-H "Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6ImNiYThhMTE0ZTM2ZDZiN2RjMmRkNjUwYTkwNGI3MmUxZjkyM2Q4ODI0NDY1MDgxNzIyM2U2MGRiNzA3ODQ3ODdkZWY1MDFmNjhhM2IxMzA3In0.eyJhdWQiOiIyIiwianRpIjoiY2JhOGExMTRlMzZkNmI3ZGMyZGQ2NTBhOTA0YjcyZTFmOTIzZDg4MjQ0NjUwODE3MjIzZTYwZGI3MDc4NDc4N2RlZjUwMWY2OGEzYjEzMDciLCJpYXQiOjE1MTI0NTcwMjUsIm5iZiI6MTUxMjQ1NzAyNSwiZXhwIjoxNTQzOTkzMDI1LCJzdWIiOiIyIiwic2NvcGVzIjpbXX0.jSTVXMy6XFXXnD1G-Jiww4uVki6P3oQQ6vCLYfMZWQRKta0F32Kdynhr7EWn5D-n8ajujSbw5GMJgYRmZdbSOp11h_zQ7HUreali0WbX5dHbh3kPLHryjgsVgKvjeLIvmmqCjnYTxz_YHav5z6h_TrrU0v_d9SrgFtz9X3aXMT_KdzPzY5QTFhF-afOhT0kTogW-R-4WdeZiUB_xqQIjh5T2QFCAzw3EQUz4ZOX1CXILVlH48Vp5su6ltZ7I2tnp6UUtMrZGpBtlpQjf7UsfYR26lOeGQLrgs2vBUtVyHc4HjSWbNAWLrMhUvcrEAXVKMOo3sOoTcNka-00P0zqAUmmMPNWvBOkh2Gs3eVmSu4gg9OS9asE6wk-wmA_3fM2N6xMw5QIiXu8EV2U3KIrIl9dABP59x8tNB7Qlfpc_vCC9HuGjsK-nfv7rU2Mo-LSAwXZBCR6guXTL4qxxuTGSjGitrE5mofAKmihSvlmBWvWfAWNBceLLpsQOhpEesdAnvhPK2fE40jQh7EAzIxRtgoFyu0vlaO3DYy0eyjfBRepxXGT_2YPpSBA674FArTa_XgFqQv5lf__qrIU0loaoRF0RYRgfKIMYRI29zKZBK68jBsiuuRxzpnoBKoXTvcmlg3E9a2Dut4acO5P7qEHanEhGo1tA14yg9i6RtrpCaZM" \
-H "User-Agent: ios-app/1.0 (com.coderspeak.matchmaking.ios-app; build:1; iOS 9.3.5) Alamofire/4.5.1" \
-H "Accept: application/json" \
"http://some.net/url/to/post/the/data/model"
===========RESPONSE=============
[Request]: POST http://some.net/url/to/post/the/data/model
[Response]: <NSHTTPURLResponse: 0x14e2c890> URL: http://some.net/url/to/post/the/data/model status code: 200, headers
"Cache-Control" = "no-cache, private";
Connection = "Keep-Alive";
"Content-Length" = 762;
"Content-Type" = "application/json";
Date = "Fri, 15 Dec 2017 14:43:26 GMT";
"Keep-Alive" = "timeout=5, max=100";
Server = "Apache/2.4.18 (Ubuntu)";
Vary = Authorization;
"X-RateLimit-Limit" = 60;
"X-RateLimit-Remaining" = 52;
[Data]: 762 bytes
[Result]: SUCCESS:
single =
approved = 0;
email = Cfhgg;
"last_name" = Gdggdgjg;
"photo_album" =
avatar = "<null>";
"created_at" = "2017-12-15 14:43:28";
id = 157;
"photo_1" = "<null>";
"photo_2" = "<null>";
"photo_3" = "<null>";
"updated_at" = "2017-12-15 14:43:28";
;
;
我确实从返回的 json 模型中删除了几行,因为它没有添加任何内容,只会使问题变得混乱。
【问题讨论】:
能否请您在此行之后打印 user_id let userId = String(describing: self.matchmakerModels?.filter( m in m.email == self.selectedMatchmakerEmail)[0].id) 是对吗? 请求没有失败?能否请您打印您的请求和回复? @ArthurSahakyan 这是一个 Option(2),它应该是这样的。 @mihatel No. 请求成功。我将把它添加到问题中。 在邮递员 user_id=1,而不是 user_id=Optional(1) 中,即使代码中缺少另一个,它也会始终失败,但我看到你的代码等于 Curl 期望的东西,请改成这个 let userId = String(self.matchmakerModels?.filter( m in m.email == self.selectedMatchmakerEmail)[0].id!) 【参考方案1】:结果图像数据太大:) 需要压缩更多
let data = UIImageJPEGRepresentation(self.selectedImage, 0.1)
【讨论】:
以上是关于Alamofire 多部分/表单数据上传请求中仅不发送图像的主要内容,如果未能解决你的问题,请参考以下文章
使用 Alamofire 和 BOX API 的多部分表单上传