这是我的CURL的样子:
curl -X POST "http://localhost:2202/api/project" -H "accept: aplication/json" -H "key: x" -H "Content-Type: multipart/form-data" -F "project={"title":"Test Title","description":"Test description for new project","priority":false,"category_id":1,"location_id":1}" -F "images[]=@fileName.jpg;type=image/jpeg"
文本上传使用以下代码:
let parametersText = ["project":["title":requestName.text!,"description":requestDescription.text!,"priority":emergencySwitch.isOn,"category_id":selectedCategoryID,"location_id":selectedLocationID]]
var selectedImagesForUpload = [Image]()
Alamofire.upload(multipartFormData: { multipartFormData in
// Texts
for (key, value) in parametersText{
do{
let data = try JSONSerialization.data(withJSONObject: value, options: .prettyPrinted)
multipartFormData.append(data, withName: key)
}catch(let err){
print(err.localizedDescription)
}
}
},usingThreshold:UInt64.init(),
to: url,
method: .post,
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { response in
print(response.result.value)
sender.isLoading = false
self.showNotification(color: #colorLiteral(red: 0.1803921569, green: 0.8, blue: 0.4431372549, alpha: 1), title: "Success", icon: #imageLiteral(resourceName: "UploadSuccess"))
}
case .failure(let encodingError):
print(encodingError)
}})}
如何更改代码以实现多张图片上传?
答案 0 :(得分:0)
class func uploadImage(showloader : Bool,imgData : [Data],url : URL,parameters : [String : Any],success:@escaping (JSON) -> Void, failure:@escaping () -> Void ) {
if Reachability()?.isReachable == true{
if (showloader) {
SVProgressHUD.show()
}
Alamofire.upload(multipartFormData: { multipartFormData in
for imageData in imgData{
multipartFormData.append(imageData, withName: "car_image_name[0]",fileName: "\(NSDate().timeIntervalSince1970).jpg", mimeType: "image/jpg")
}
for (key, value) in parameters {
multipartFormData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key)
}
},
to: baseURL + url)
{ (result) in
switch result {
case .success(let upload, _, _):
upload.uploadProgress(closure: { (progress) in
print("Upload Progress: \(progress.fractionCompleted)")
})
upload.responseJSON { response in
guard let responseValue = response.result.value else {
if (showloader) {
SVProgressHUD.dismiss()
}
failure()
return
}
print(responseValue)
let responseJson = JSON(responseValue)
let status = CheckForSuccessApi(data: responseJson)
let resJson = JSON(response.result.value!)
switch status {
case true:
if (showloader) {
SVProgressHUD.dismiss()
}
success(resJson)
default:
print(responseJson.dictionaryObject!)
if let message = responseJson.dictionaryObject?[ApiKeys.result] as? NSDictionary{
DELEGATE.window?.rootViewController?.showAlertView(alertTitle: stringConstants.alerts.Error, msgString: message.value(forKey: ApiKeys.message) as! String)
}
if (showloader) {
SVProgressHUD.dismiss()
}
failure()
}
}
case .failure(let encodingError):
print(encodingError)
let error : Error = encodingError
if (showloader) {
SVProgressHUD.dismiss()
}
failure()
}
}
}else{
//display no internet available message
DELEGATE.window?.rootViewController?.showAlertView(alertTitle: stringConstants.alerts.NetworkError, msgString: stringConstants.alerts.NoInternetMsg)
}
}
答案 1 :(得分:0)
尝试以下解决方案:
var headers = ["Content-Type" : "application/json"]
headers["Authorization"] = "token"
var backgroundSessionManager: Alamofire.SessionManager
backgroundSessionManager.upload(multipartFormData: { (multipartFormData) in
for (_,image) in arrImage.enumerated()
{
if image != nil
{
//Change file parameter
multipartFormData.append(image!.jpegData(compressionQuality: 0.8)!, withName: imageKey, fileName: "image.jpg", mimeType: "image/jpeg")
// multipartFormData.append(UIImageJPEGRepresentation(image!, 0.8)!, withName: imageKey, fileName: "image.jpg", mimeType: "image/jpeg")
}
}
// for multiple videos
if arrVideo != nil
{
for (_,urll) in arrVideo!.enumerated()
{
multipartFormData.append(urll, withName: imageKey, fileName: "video.mp4", mimeType: "video/mp4")
}
}
for (key, value) in parameter
{
if value is String {
multipartFormData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key)
}
else if value is Bool{
multipartFormData.append((value as AnyObject).description.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue))!, withName: key)
}
} }, to: "", headers: headers) { (result) in
// handle response
switch result{
// handle response from server
case .success(let upload, _, _):
upload.responseJSON { response in
// handle result
}
// handle failure such network etc...
case .failure(let encodingError):
print(encodingError)
// remove loader
} }
答案 2 :(得分:0)
使用递归:-
let noOfImage = 5
var coutUpload = 0
func uploadData(){
Alamofire.upload(multipartFormData: { multipartFormData in
}, usingThreshold:UInt64.init(),
to: uploadUrl,
method: .post,
headers: header,
encodingCompletion: {(result) in
switch result{
case .success(let upload, _, _):
upload.responseJSON(completionHandler: { (res) in
if res.result.isSuccess{
if coutUpload == noOfImage{
//Uploaded All Images sucessfully
}else{
coutUpload += 1
uploadData()
}
}else{
//ERROR SHOW
}
})
break
case .failure(let encodingError):
print("the error is : \(encodingError.localizedDescription)")
break
}
})
}