How to upload multipart with this data - ios

I want to send this data in the form of multipart to server with image/video. I have image/video data in byte data form (NSData or Data)
{"mediauploadata":
{
"type":"poll",
"server_token":"03f0e635b4c01b9f398de393259de8650b54c85c24f49998af50593643f559230d95e8e605612653769f4871b543e25d48bf",
"id":"105"
}
}

I have created a function for Multipart Upload using Alamofire.
Call this function passing Web service URL , Parameters and your image.
func WSPostAPIMultiPart(_ aStrULR:String,
param: [String: Any],
image : UIImage?,
controller: UIViewController,
successBlock: #escaping (_ response:[String : Any]?) -> Void,
failureBlock: #escaping (_ error: Error?) -> Void) {
var dictHeaders : HTTPHeaders = [String : String]()
if (Alamofire.NetworkReachabilityManager()?.isReachable)!{
Alamofire.upload(
multipartFormData: { MultipartFormData in
let JSONData: Data? = try? JSONSerialization.data(withJSONObject: param, options: .prettyPrinted)
MultipartFormData.append(JSONData!, withName: "json")
if image != nil{
MultipartFormData.append(UIImageJPEGRepresentation(image!, 0.5)!, withName: "profile_image",fileName: "image.jpeg", mimeType: "image/jpeg")
// withName : You will pass the key name required by your server
}
}, to: aStrULR ,method : .post , headers : dictHeaders) { (result) in
switch result {
case .success(let upload, _, _):
upload.responseJSON { response in
if let value = response.result.value {
let dictResponse = JSON(value).dictionaryObject
successBlock(dictResponse)
}
}
case .failure(let error):
failureBlock(error)
}
}
}else{
print("NO INTERNET CONNECTIVITY")
}
}
For Video: Just pass videoURL one extra parameter and append as :
MultipartFormData.append(videoUrl, withName: "profileVideo", fileName: "video.mp4", mimeType: "video/mp4")
Hope it helps :)

func uploadDataWith(parameter params:Dictionary<String,String>,data:Data?,isImage:Bool,handler:#escaping ((Dictionary<String,Any>?) -> Void)) {
Alamofire.upload(multipartFormData: { (multipartFormData) in
for (key, value) in params {
multipartFormData.append(value.data(using: String.Encoding.utf8, allowLossyConversion: false)!, withName: key)
}
if data != nil && isImage {
multipartFormData.append(data, withName: "photo_upload", fileName: "file.png", mimeType: "image/png")
}
if data != nil && !isImage {
multipartFormData.append(data, withName: "video_upload", fileName: "file.mp4", mimeType: "video/mp4")
}
}, to: "http://") { (encodingResult) in
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { response in
switch response.result {
case .success:
if let jsonDict = response.result.value as? Dictionary<String,Any> {
print("Json Response: \(jsonDict)")
handler(jsonDict)
print(jsonDict,(response.response!.statusCode))
}
else{
print(response.response!.statusCode)
handler(nil)
}
if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {
print("Server Response: \(utf8Text)") // original server data as UTF8 string
}
break
case .failure(let error):
print(response.response!.statusCode)
print_debug(error)
handler(nil)
break
}
}
case .failure(let encodingError):
print(encodingError)
}
}
}

Related

iOS : How to upload multiple images to server using multipart using alamofire

I have to upload multiple images to the server through alamofire. I am able to get the images in the form of array, convert them to data but when i upload them to the server only first image is appearing.
I am sharing my code please help.
i am getting image array of this type
image array== [<UIImage:0x2804cb210 anonymous {1170, 2532}
renderingMode=automatic(original)>, <UIImage:0x2804f03f0 anonymous
{1170, 2532} renderingMode=automatic(original)>]
and when i convert it to data from the code i got this response
print("image array==", self.images)
self.photoImageData = self.images.compactMap { $0.pngData() }
print("====", photoImageData)
==== [4074684 bytes, 1353198 bytes]
here is my function
func hitPostAPIWithprofileImageArray(urlString: String, params: [String: String],imageData: [Data],imageKey: String, completionHandler:#escaping (_ result: [String: Any], _ errorC : Error?) -> Void)
{
print("params-> ",params)
let openUrl : URL
openUrl = URL(string: baseURL + urlString)!
print("params-> ",openUrl)
Alamofire.upload(
multipartFormData: { multipartFormData in
for imageData in imageData {
multipartFormData.append(imageData, withName: imageKey, fileName: "user.jpg", mimeType: "image/jpeg")
}
for (key, value) in params {
multipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
}
},
to: openUrl,
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { response in
debugPrint(response)
do{
let result = try JSONSerialization.jsonObject(with: response.data!, options: JSONSerialization.ReadingOptions.allowFragments) as! [String:Any]
print(result)
let errorC = Error.self
completionHandler(result,errorC as? Error)
}catch{
if let err = response.error {
completionHandler(self.resultG,err as? Error); return
}
} }
upload.uploadProgress(queue: DispatchQueue(label: "uploadQueue"), closure: { (progress) in
})
case .failure(let encodingError):
print(encodingError)
completionHandler(self.resultG,encodingError as? Error)
}
}
)
}

Alamofire multipart upload giving error

I am trying to upload an image to server using Alamofire Multipart Form data however upon execution iam getting error as
exception 'NSInvalidArgumentException', reason: '-[__NSCFNumber
dataUsingEncoding:]: unrecognized selector sent to instance
0x1669e250'
in the line
MultipartFormData.append(((value as AnyObject).data(using: String.Encoding.utf8.rawValue))!, withName: key)
below is my full code
guard let image = selectedImage else {
return
}
let heightInPixels = Int(image.size.height * image.scale)
let widthInPixels = Int(image.size.width * image.scale)
let parameters: Parameters = ["user_id": Utility().getBearerToken(),"description": descriptionTextView.text ?? "",
"lat": self.lat ?? "" , "long":self.long ?? "" ,
"location_name": locationTextView.text ?? "" ,
"height": heightInPixels, "width": widthInPixels];
// let parameters: Parameters = ["user_id": Utility().getBearerToken()];
print(parameters)
Alamofire.upload(multipartFormData: { MultipartFormData in
for (key, value) in parameters {
MultipartFormData.append(((value as AnyObject).data(using: String.Encoding.utf8.rawValue))!, withName: key)
}
let imgData = UIImageJPEGRepresentation(image,1)
MultipartFormData.append(imgData!, withName: "file", fileName: "upload.jpg", mimeType: "image/jpeg")
}, to: "http://server.com/upload.php") { (result) in
switch result {
case .success(let upload, _, _):
upload.uploadProgress(closure: { (Progress) in
print("Upload Progress: \(Progress.fractionCompleted)")
})
upload.responseString { response in
print(response.result.value!)
}
case .failure(let encodingError):
print(encodingError.localizedDescription)
break
}
}
I tried with MultipartFormData.append(value.data(using: .utf8)!, withName: name!) but it says value has no member data
Try this below func, it is working.
func uploadImage(urlString : String , image : UIImage, param : [String : Any], completionHandler : #escaping ( _ result : Any?) -> ()) {
guard let imageData = UIImageJPEGRepresentation(image, 0.5) else {
print("Could not get JPEG representation of UIImage")
return
}
Alamofire.upload(multipartFormData: { multipartFormData in
for (key, value) in param {
multipartFormData.append("\(value)".data(using: String.Encoding.utf8)!, withName: key as String)
}
multipartFormData.append(imageData,
withName: "image",
fileName: "image.jpg",
mimeType: "image/jpeg")
},
to: urlString,
headers: ["Authorization": "Basic xxx"],
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.uploadProgress { progress in
}
upload.validate()
upload.responseJSON { response in
completionHandler(response.result.value)
}
case .failure(let encodingError):
print(encodingError)
completionHandler(nil)
}
})
}
Here is the function for upload video and image with your other API Parameters.
func uploadWithAlamofire(Parameters params : [String: Any]?,ImageParameters imgparams : [NSObject : AnyObject]?,VideoParameters vidoparam : [NSObject : AnyObject]?,Action action : NSString, success: #escaping (AnyObject) -> Void, failure: #escaping (AnyObject) -> Void)
{
var base_url = BASEURL
base_url.append(action as String)
print(base_url)
var headers : HTTPHeaders = [:]
if let token = UserDefaults.standard.value(forKey: "webToken"){
headers = ["JWT-Authorization": "Bearer \(token)"]
}
Alamofire.upload(multipartFormData: { multipartFormData in
if imgparams != nil{
for (key, value) in imgparams! {
if let imageData = UIImageJPEGRepresentation(value as! UIImage, 1) {
multipartFormData.append(imageData, withName: key as! String, fileName: "\(NSDate().timeIntervalSince1970 * 1000)).jpg", mimeType: "image/jpg")
}
}
}
if vidoparam != nil{
for (key, value) in vidoparam! {
multipartFormData.append(value as! URL , withName: key as! String, fileName: "\(NSDate().timeIntervalSince1970 * 1000).mp4", mimeType: "application/octet-stream")
}
}
if params != nil
{
for (key, value) in params! {
multipartFormData.append((value as! String).data(using: .utf8)!, withName: key as! String)
}
} }, to: base_url, method: .post, headers: headers,
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.uploadProgress { progress in
print(progress.fractionCompleted)
}
upload.response { [weak self] response in
guard self != nil else {
return
}
let responseString = String(data: response.data!, encoding: String.Encoding.utf8)
var dictonary:NSDictionary?
if let data = responseString?.data(using: String.Encoding.utf8) {
do {
dictonary = try JSONSerialization.jsonObject(with: data, options: []) as? [String:AnyObject] as NSDictionary?
if dictonary != nil{
if dictonary?.value(forKey: "status_code") as! String == "200"{
return success(dictonary!)
}else{
print(dictonary?.value(forKey: "status_code")! as Any)
let errorMsg : Any = Int(dictonary?.value(forKey: "status_code") as Any)
utility.showAlertWithStatusCode(code: errorMsg)
}
}
} catch let error as NSError {
print(error)
}
}
}
case .failure(let encodingError):
print("error:\(encodingError)")
return failure(encodingError as AnyObject)
}
})
}

File upload issue in ios

I have a problem uploading a Document file through Document picker controller. I have selected File through Document picker. and send file using multipart data in service. but xcode give some error in ios swift.
Here is my code For Image upload.
Alamofire.upload(multipartFormData: { (multipartFormData) in
for (key, value) in params {
multipartFormData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key)
}
multipartFormData.append(imageData!, withName: "upload_photo", fileName: "img.png", mimeType: "image/jpeg")
}, to:pageURL)
{ (result) in
switch result {
case .success(let upload, _, _):
self.stopLoader()
upload.uploadProgress(closure: { (Progress) in
print("Upload Progress: \(Progress.fractionCompleted)")
})
But i have to upload Document file from url.
Use my below class it is simple and manageable and working file :
import UIKit
import Alamofire
class TDWebServices: NSObject {
static let shared = TDWebServices()
func post(urlString : String , param : [String : Any], completionHandler : #escaping ( _ result : Any?) -> ()) {
Alamofire.request(urlString, method: .post, parameters: param, encoding: JSONEncoding.default, headers: ["Accept": "application/json"]).responseJSON { (response) in
switch response.result {
case .success:
let json = response.result.value as? NSDictionary
completionHandler(json)
case .failure(let error):
print(error)
completionHandler(nil)
return
}
}
}
func uploadImage(urlString : String , image : UIImage, param : [String : Any], completionHandler : #escaping ( _ result : Any?) -> ()) {
guard let imageData = UIImageJPEGRepresentation(image, 0.5) else {
print("Could not get JPEG representation of UIImage")
return
}
let header: HTTPHeaders = [
"Content-type": "multipart/form-data"
]
Alamofire.upload(multipartFormData: { multipartFormData in
for (key, value) in param {
multipartFormData.append("\(value)".data(using: String.Encoding.utf8)!, withName: key as String)
}
multipartFormData.append(imageData,
withName: "image", // <- It is param for uploading the file make sure it is perfect as per your API
fileName: "image.jpg",
mimeType: "image/jpeg")
},
to: urlString,
headers: header, // ["Authorization": "Basic xxx"]
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.uploadProgress { progress in
// progressCompletion(Float(progress.fractionCompleted))
}
upload.validate()
upload.responseJSON { response in
completionHandler(response.result.value)
}
case .failure(let encodingError):
print(encodingError)
completionHandler(nil)
}
})
}
}
How to use?
let param = ["user_id" : 123 as Any] // Whatever your params are
// showActivity() // <- show activity indicator
TDWebServices.shared.post(urlString: <your_api_url>, param: param) { (res) in
// hideActivity() // <- hide activity indicator
if res != nil{
let aDict = res as? [String : Any] // your response
// Hnadle your code here
}
else{
self.showAlert(title: "Invalid!", message: "Internet connection issue.", calcelHandler: {}) // <- If you have internet issue
}
}
Still facing issue then let me know..

How to upload image using Alamofire with token&parameters?

I use Alamofire to upload images, however the upload is unsuccessful. I also bring token & parameters to server.
I don't know whether I add token & parameters correctly or not.
What's wrong with me to using Alamofire?
Have any suggestion?
Thanks.
func uploadWithAlamofire(image:UIImage, imageData:Data, imageUrl:URL) {
let parameters = ["avatar":imageData]
Alamofire.upload(multipartFormData: { multipartFormData in
multipartFormData.append(imageData, withName: user.id, fileName: "\(user.id).jpg", mimeType: "image/jpg")
for (key, value) in parameters {
multipartFormData.append(value, withName: key)
}
}, to: apiUrl , method: .put, headers: ["Authorization": "Bearer \(token)"],
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.response { [weak self] response in
guard self != nil else {
return
}
debugPrint(response)
}
case .failure(let encodingError):
print("error:\(encodingError)")
}
})
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
photoImage = info[UIImagePickerControllerOriginalImage] as! UIImage
photoImageView.image = photoImage
let imageName:String = user.id + ".jpg"
let documentsPath = NSHomeDirectory().appending("/Documents/Icon/")
let imagePath = documentsPath.appending(imageName)
let imageUrl = URL(fileURLWithPath: imagePath)
print("imageUrl is here:\(imageUrl)")
let imageData:Data = UIImageJPEGRepresentation(photoImage, 0.001)!
do {
try imageData.write(to: imageUrl,options: .atomic)
} catch let error {
print(error)
}
uploadWithAlamofire(image: photoImage, imageData: imageData, imageUrl: imageUrl)
self.dismiss(animated: true, completion: nil)
}
Try this:
func uploadImageWith(param params:Dictionary<String,String>,image:UIImage?,handler:#escaping ((Dictionary<String,Any>?,Int) -> Void)) {
// let keyJson = "json".dataUsingEncoding(NSUTF8StringEncoding)!
print("Params:\(params)")
let BASE_URL = "http://"
Alamofire.upload(
multipartFormData: { multipartFormData in
for (key, value) in params {
multipartFormData.append(value.data(using: String.Encoding.utf8, allowLossyConversion: false)!, withName: key)
}
if image != nil{
let imgData = UIImageJPEGRepresentation(image!, 0.5)
if imgData != nil {
multipartFormData.append(imgData!, withName: "photo_upload", fileName: "file.png", mimeType: "image/png")
}
}
},
to: BASE_URL,
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { response in
switch response.result {
case .success:
if let jsonDict = response.result.value as? Dictionary<String,Any> {
print_debug("Json Response: \(jsonDict)") // serialized json response
handler(jsonDict,(response.response!.statusCode))
}
else{
handler(nil,(response.response!.statusCode))
}
if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {
print("Server Response: \(utf8Text)") // original server data as UTF8 string
}
break
case .failure(let error):
handler(nil,(response.response!.statusCode))
break
}
}
case .failure(let encodingError):
print(encodingError)
}
}
)
}
USE
uploadImageWith(param: ["key":"value"], image: UIImage(name:"icon")) { (response, statusCode) in
print(response)
}
You have to pass the params and image object and you get the response as a Dictionary object in closure.
Use this function to upload image to the server with token and parameters
func uploadImageAndData(){
var parameters = [String:AnyObject]()
parameters = ["token": token,
"Name": Name]
let URL = "http://yourserviceurl/"
let image = UIImage(named: "image.png")
Alamofire.upload(.POST, URL, multipartFormData: {
multipartFormData in
if let imageData = UIImageJPEGRepresentation(image, 0.6) {
multipartFormData.appendBodyPart(data: imageData, name: "image", fileName: "file.png", mimeType: "image/png")
}
for (key, value) in parameters {
multipartFormData.appendBodyPart(data: value.dataUsingEncoding(NSUTF8StringEncoding)!, name: key)
}
}, encodingCompletion: {
encodingResult in
switch encodingResult {
case .Success(let upload, _, _):
print("s")
upload.responseJSON {
response in
print(response.request) // original URL request
print(response.response) // URL response
print(response.data) // server data
print(response.result) // result of response serialization
if let JSON = response.result.value {
print("JSON: \(JSON)")
}
}
case .Failure(let encodingError):
print(encodingError)
}
})}
Works for the Alamofire 3.0+

Upload Photo / File with JSON and custom headers via Swift 3 and Alamofire 4 | iOS | Swift

I need to call the Multipart request with Image file and JSON.
I have tried this, but still getting the error.
// define parameters
let parameters = [
"hometown": "yalikavak",
"living": "istanbul"
]
Alamofire.upload(multipartFormData: { multipartFormData in
if let imageData = UIImageJPEGRepresentation(image, 1) {
multipartFormData.append(imageData, withName: "file", fileName: "file.png", mimeType: "image/png")
}
for (key, value) in parameters {
multipartFormData.append((value?.data(using: .utf8))!, withName: key)
}}, to: "upload_url", method: .post, headers: ["Authorization": "auth_token"],
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.response { [weak self] response in
guard let strongSelf = self else {
return
}
debugPrint(response)
}
case .failure(let encodingError):
print("error:\(encodingError)")
}
})
}
How to send the JSON?
Try This Code for Multiple upload Images in Single Request, This code is already working.
// For Pass Valid Parameters & number of Images in Array in Image Upload Function
var dicImgData : NSMutableDictionary? = NSMutableDictionary()
if let img = UIImage(named: "Your Image") {
if let data:Data = UIImagePNGRepresentation(img) {
var imageData : NSData = data
dicImgData! .setObject(imageData, forKey: "data" as NSCopying)
dicImgData! .setObject("file", forKey: "name" as NSCopying)
dicImgData! .setObject("file.png", forKey: "fileName" as NSCopying)
dicImgData! .setObject("image/png", forKey: "type" as NSCopying)
let dicParameter = [
"hometown": "yalikavak",
"living": "istanbul"
]
self.uploadImage(url: "Your URL", Parameter: dicParameter, Images: [dicImgData])
}
}
Upload Function
func uploadImage (url: String, Parameter param : NSDictionary, Images arrImage: NSArray) -> Void
{
var requestURL : String! = url
let headers = [
"Authorization": "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==",
"Accept": "application/json",
]
print("---------------------")
print("Request URL :- \(requestURL)")
print("---------------------")
Alamofire.upload(multipartFormData: { (data) in
for (key, value) in param {
data.append((value as! String).data(using: .utf8)!, withName: key as! String)
}
for imageInfo in arrImage
{
var dicInfo : NSDictionary! = imageInfo as! NSDictionary
data.append(dicInfo["data"] as! Data, withName: dicInfo["name"] as! String, fileName: dicInfo["fileName"] as! String, mimeType: dicInfo["type"] as! String)
dicInfo = nil
}
}, to: requestURL, method: .post , headers:nil, encodingCompletion: { (encodeResult) in
switch encodeResult {
case .success(let upload, _, _):
upload.responseJSON(completionHandler: { (response) in
switch response.result
{
case .success(let responseJSON):
guard let dicResponse = responseJSON as? NSDictionary else{
return
}
print("Response : \((dicResponse))")
case .failure(let error):
print(error)
break
}
})
case .failure(let error):
print(error)
break
}
})
}
From data you have given, I comes to an conclusion as given below.
The status code 400 means json you're passing to the api was not following the api documentation. For example if they expect a key "name" and you're not given such a key at all.
Other possible reasons for this error.
Seems like you haven't mentioned any of content types
Add these line of code to assure that the response and your request are in proper formats
Alamofire.request(.GET, "your url", parameters: ["foo": "bar"])
.validate(statusCode: 200..<300)
.validate(contentType: ["application/json"])
.response { (_, _, _, error) in
println(error)
}
The Accept header tells the server what your client wants in the
response. The Content-Type header tells the server what the client
sends in the request.
If you can give more information we can help further.
Here I made my custom webservice, You can use it. This webservice is for upload dictionary with image and video or both or without it.
import Foundation
import Alamofire
class WebServiceHandler: AnyObject {
func uploadWithAlamofire(Parameters params : [NSObject : AnyObject]?,ImageParameters imgparams : [NSObject : AnyObject]?,VideoParameters vidoparam : [NSObject : AnyObject]?,Action action : NSString, success: #escaping (AnyObject) -> Void, failure: #escaping (AnyObject) -> Void)
{
var base_url = "http://benzatineinfotech.com/webservice/finder/index.php/Web_api/"
base_url.append(action as String)
Alamofire.upload(multipartFormData: { multipartFormData in
if imgparams != nil{
for (key, value) in imgparams! {
if let imageData = UIImageJPEGRepresentation(value as! UIImage, 1) {
multipartFormData.append(imageData, withName: key as! String, fileName: "\(NSDate().timeIntervalSince1970 * 1000)).jpg", mimeType: "image/jpg")
}
}
}
if vidoparam != nil{
for (key, value) in vidoparam! {
multipartFormData.append(value as! URL , withName: key as! String, fileName: "\(NSDate().timeIntervalSince1970 * 1000).mp4", mimeType: "application/octet-stream")
}
}
if params != nil
{
for (key, value) in params! {
multipartFormData.append((value as! String).data(using: .utf8)!, withName: key as! String)
}
} }, to: base_url, method: .post, headers: nil,
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.uploadProgress { progress in
print(progress.fractionCompleted)
}
upload.response { [weak self] response in
guard self != nil else {
return
}
let responseString = String(data: response.data!, encoding: String.Encoding.utf8)
return success(responseString as AnyObject)
}
case .failure(let encodingError):
print("error:\(encodingError)")
return failure(encodingError as AnyObject)
}
})
}
func convertToDictionary(text: String) -> [String: Any]? {
if let data = text.data(using: .utf8) {
do {
return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
} catch {
print(error.localizedDescription)
}
}
return nil
}
}
Usage:
self.webservice.uploadWithAlamofire(Parameters: dict_params as [NSObject : AnyObject], ImageParameters: imgparam as [NSObject : AnyObject], VideoParameters: videoparam as [NSObject : AnyObject], Action: "write_message", success: { (success) in
print(success)
}) { (error) in
print(error)
}

Resources