[英]How to send array in params using Alamofire multipart from data using swift 4
我正在使用Alamofire
將圖像和文件上傳到服務器。 但是我在發送帶有圖像的參數數組時遇到問題。 但是當我在 params 中發送一個數組時,它會將數組轉換為JSON
字符串。 但我想在 params 中發送一個數組,而不是在JSON
字符串中。 我已經搜索了很多,但沒有得到任何解決方案。 這是下面的代碼。
let params = ["id":"101","arrayParam":["1232","12344","14325"]]
let url = www.khxjjhdfsj.com/hsdgs
let headers: HTTPHeaders = [
/* "Authorization": "your_access_token", in case you need authorization header */
"Content-type": "multipart/form-data"
]
Alamofire.upload(multipartFormData: { (multipartFormData) in
for (key, value) in params
{
multipartFormData.append("\(value)".data(using: String.Encoding.utf8)!, withName: key as String)
}
if let data = imageData
{
multipartFormData.append(data, withName: "file", fileName: fileName, mimeType: "image/png")
}
if let data = pdfData
{
multipartFormData.append(data, withName: "file", fileName: fileName, mimeType:"application/pdf")
}
}, usingThreshold: UInt64.init(), to: url, method: .post, headers: headers) { (result) in
switch result{
case .success(let upload, _, _):
upload.responseJSON { response in
print("Succesfully uploaded")
if let err = response.error
{
onError?(err)
return
}
}
case .failure(let error):
print("Error in upload: \(error.localizedDescription)")
onError?(error)
}
}
你能試試這個嗎,也許你會得到
var dict = Data()
let params:[String:Any] = ["id":"101","arrayParam":["1232","12344","14325"]]
for (key, value) in params {
if key == "arrayParam" {
if let str:[String] = value as? [String]{
// to convert [String] to data
dict = Data(buffer: UnsafeBufferPointer(start: str, count: str.count))
// to retrive [String] from data
let arr2 = dict.withUnsafeBytes {
Array(UnsafeBufferPointer<String>(start: $0, count: dict.count/MemoryLayout<String>.stride))
}
print(arr2)
}
}
multipartFormData.append(dict, withName: key)
}
let params = [
"key":value,
"key1": key2] as [String : Any]
let manager = Alamofire.SessionManager.default
manager.session.configuration.timeoutIntervalForRequest = 30000
manager.request(url, method: .post, parameters: params)
.responseJSON {
response in
switch response.result {
case .success:
stopActivityIndicator()
print(response)
if let result = response.result.value {
let JSON = result as! NSDictionary
print(JSON)
let ResponseSuccess = JSON.object(forKey: "response")!
self.displayAlert(Message: ResponseSuccess as! String, myView:self)
}
case .failure( _):
if let result = response.result.value {
stopActivityIndicator()
let JSON = result as! NSDictionary
print(JSON)
let ResponseFail = JSON.object(forKey: "response")!
self.displayAlert(Message: ResponseFail as! String, myView:self)
}
}
}
我沒有看到任何被接受的答案,所以分享我的解決方案。 它已經過測試並且可以正常工作。
let arrayObj = value as !Array<Any>
for i in 0..< arrayObj.count {
let value = arrayObj[i] as !String
let keyObj = key + "[" + String(i) + "]"
form.append(value.data(using: String.Encoding.utf8)!, withName: keyObj)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.