使用Alamofire快速上传多张图片

我正在使用以下代码将单个图像上传到服务器:

private static func urlRequestWithComponents(urlString:String, parameters:Dictionary<String, String>, imageData:NSData?, imageName: String) -> (URLRequestConvertible , NSData) {

// create url request to send

let mutableURLRequest = NSMutableURLRequest(URL: NSURL(string: urlString)!)

mutableURLRequest.HTTPMethod = Alamofire.Method.POST.rawValue

let boundaryConstant = "myRandomBoundary12345";

let contentType = "multipart/form-data;boundary="+boundaryConstant

mutableURLRequest.setValue(contentType, forHTTPHeaderField: "Content-Type")

// create upload data to send

let uploadData = NSMutableData()

if(imageData != nil && imageData?.length != 0) {

// add image

uploadData.appendData("\r\n--\(boundaryConstant)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)

uploadData.appendData("Content-Disposition: form-data; name=\"\(imageName)\"; filename=\"\(StringHelper.sharedInstance.randomString(5)).png\"\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)

uploadData.appendData("Content-Type: image/png\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)

uploadData.appendData(imageData!)

}

// add parameters

for (key, value) in parameters {

uploadData.appendData("\r\n--\(boundaryConstant)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)

uploadData.appendData("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n\(value)".dataUsingEncoding(NSUTF8StringEncoding)!)

}

uploadData.appendData("\r\n--\(boundaryConstant)--\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)

print("upload",parameters)

// return URLRequestConvertible and NSData

return (Alamofire.ParameterEncoding.URL.encode(mutableURLRequest, parameters: nil).0, uploadData)

}

如何通过编辑此代码在单个参数中上传多张图片?

回答:

只需在图像上传参数中使用“ []”即可使其成为图像数组。

Alamofire.upload(multipartFormData: { multipartFormData in

// import image to request

for imageData in imagesData {

multipartFormData.append(imageData, withName: "\(imageParamName)[]", fileName: "\(Date().timeIntervalSince1970).jpeg", mimeType: "image/jpeg")

}

for (key, value) in parameters {

multipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)

}

}, to: urlString,

encodingCompletion: { encodingResult in

switch encodingResult {

case .success(let upload, _, _):

upload.responseJSON { response in

}

case .failure(let error):

print(error)

}

})

以上是 使用Alamofire快速上传多张图片 的全部内容, 来源链接: utcz.com/qa/419778.html

回到顶部