Upload audio binary file using Alamofire - swift

I'm trying to upload an audio binary file to a server using Alamofire along with parameters and headers. Whenever I add the parameters; I get an error saying ambigious reference call to member error. I have checked the API online and haven't found a way to pass in parameters. Is there a way to do so?
let headersFileUpload: HTTPHeaders = ["Authorization": "JWT "+token!]
let parametersFileUpload: Parameters = ["ctype":"yes"]
Alamofire.upload(
multipartFormData: { multipartFormData in
multipartFormData.append(self.getDocumentsDirectory().appendingPathComponent("recording.m4a"), withName: "iosTest.mp3")
},
to: "http://localhost:8000/api/upload",
method:.post,
headers:headersFileUpload,
parameters:parametersFileUpload
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { response in
debugPrint(response)
}
case .failure(let encodingError):
print(encodingError)
}
}
)

Related

Multipart form data upload with Alamofire shows file missing in server

I'm trying to upload an image using Alamofire, the response shows success but the picture doesn't get uploaded. When I debugged with backend developer, it seemed the file attachment is missing in the request. However, the progress shows uploading details of the file. Can anyone help what's going wrong here.
class ImageUploadClient {
class func upload(image: UIImage, to request: URLRequest) {
let imgData = UIImageJPEGRepresentation(image, 0.5)!
let filename = "file.jpeg"
Alamofire.upload(multipartFormData: { (multiPartData) in
multiPartData.append(imgData, withName: filename, mimeType: "image/jpg")
}, usingThreshold: UInt64(1024),
with: request, encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let request, let streamingFromDisk, let fileURL):
debugPrint(streamingFromDisk) // Shows true
debugPrint(fileURL) // Returns file url
debugPrint(request)
// upload progress closure
request.uploadProgress(closure: { (progress) in
print("upload progress: \(progress.fractionCompleted)")
// here you can send out to a delegate or via notifications the upload progress to interested parties
})
// response handler
request.validate()
.responseJSON(completionHandler: { (response) in
switch response.result {
case .success(let value):
debugPrint(value)
case .failure(let err):
debugPrint(err)
}
})
// encodingResult failure
case .failure(let error):
debugPrint(error)
}
})
}
}
try by adding file name for your image
like this
and withName key will contain Key name to your image on server
let profileKey = "profileImage"
multiPartData.append(imgData, withName: profileKey, fileName: filename, mimeType: "image/jpg")

How to upload PDF file in swift using form-data or any other method

can we upload pdf/doc file using form-data in swift. Or any other way to upload. if possible please provide working example as i am new in this technology.
Its good to use excellent Alamofire library to upload any doc (such as pdf file).The below code will explain how to use alamofire to upload a file
Alamofire.upload(
multipartFormData: {
multipartFormData in
if let urlString = urlBase2 {
let pdfData = try! Data(contentsOf: urlString.asURL())
var data : Data = pdfData
multipartFormData.append(pdfData, withName: "pdfDocuments", fileName: namePDF, mimeType:"application/pdf")
for (key, value) in body {
multipartFormData.append(((value as? String)?.data(using: .utf8))!, withName: key)
}
print("Multi part Content -Type")
print(multipartFormData.contentType)
print("Multi part FIN ")
print("Multi part Content-Length")
print(multipartFormData.contentLength)
print("Multi part Content-Boundary")
print(multipartFormData.boundary)
}
},
to: url,
method: .post,
headers: header,
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { response in
print(" responses ")
print(response)
print("Responses ended")
onCompletion(true, "Something went wrong", 200)
}
case .failure(let encodingError):
print(encodingError)
onCompletion(false, "Something went wrong", 200)
}
})

Type of expression is ambiguous without more context in Alamofire.upload swift 3

Updated Alamofire 4.0.0 does not mention how to put Httpmethod & Httpheaders in upload with multipartFormData. That's why I google and found solution in that stackoverflow question. But the problem is I did same as that answer then got following error message and building is failed. Please help me how to solve it.
Type of expression is ambiguous without more context
Here is my coding:
let URL = try! URLRequest(url: Config.imageUploadURL, method: .post, headers: headers)
Alamofire.upload(
multipartFormData: { multipartFormData in
multipartFormData.append(self.imageData, withName: "image", fileName: "file.png", mimeType: "image/png")
},
to: URL,
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { response in
if((response.result.value) != nil) {
} else {
}
}
case .failure( _):
}
}
)
Alamofire.upload(multipartFormData:to:encodingCompletion:) takes a URLConvertible for the to: argument. Instead, you should use Alamofire.upload(multipartFormData:with:encodingCompletion:) which takes a URLRequestConvertible for its with: argument.
I think your argument name of URL that is the same as the type URL() helps in creating strange compiler errors.
The following compiles for me:
let url = try! URLRequest(url: URL(string:"www.google.com")!, method: .post, headers: nil)
Alamofire.upload(
multipartFormData: { multipartFormData in
multipartFormData.append(Data(), withName: "image", fileName: "file.png", mimeType: "image/png")
},
with: url,
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { response in
if((response.result.value) != nil) {
} else {
}
}
case .failure( _):
break
}
}
)
For me the build error was caused by a multipartFormData.appendBodyData(). After replacing it with multipartFormData.append() the problem was solved.
I got the same error, after spending lots of time, i found that issue was:
I was passing MutableURLRequest instead of passing URLRequest object. Thats why i were getting this error. After type casting it to URLRequest, it start working.

How to upload an arbitrary number of files with Swift and Alamofire?

I'm trying to access a REST API which lets me upload a different number of files, depending on the situation. I've got the following code for Alamofire but I'm not sure how to change this so that I can upload one file, two files, or ten files.
Alamofire.upload(
.POST,
"https://httpbin.org/post",
multipartFormData: { multipartFormData in
multipartFormData.appendBodyPart(fileURL: farmFileURL, name: "xml-file-farm")
multipartFormData.appendBodyPart(fileURL: farmFileURL, name: "csv-measurement-file-1")
multipartFormData.appendBodyPart(fileURL: farmFileURL, name: "csv-measurement-file-2")
},
encodingCompletion: { encodingResult in
switch encodingResult {
case .Success(let upload, _, _):
upload.responseJSON { response in
debugPrint(response)
}
case .Failure(let encodingError):
print(encodingError)
}
}
)
The problem as I see it is that I can't define an array of files using 'multipartFormData' because that doesn't exist until you're inside the 'upload' method.
Make an array of Tuple which contains fileName and its URL and simply pass it:
func uploadFiles(files:[(String,NSURL)]){
Alamofire.upload(
.POST,
"https://httpbin.org/post",
multipartFormData: { multipartFormData in
for (fileName, fileURL) in files{
multipartFormData.appendBodyPart(fileURL: fileURL, name: fileName)
}
},
encodingCompletion: { encodingResult in
switch encodingResult {
case .Success(let upload, _, _):
upload.responseJSON { response in
debugPrint(response)
}
case .Failure(let encodingError):
print(encodingError)
}
}
)
}

How to upload image with Alamofire from camera roll

I am having trouble uploading image with Alamofire. Problem is very simple - I do not know how get fileURL(NSURL) for a selected image.
Here is simple code from Alamofire GitHub:
Alamofire.upload(
.POST,
"myCustomServerURL",
multipartFormData: { multipartFormData in
multipartFormData.appendBodyPart(data: "_formname".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name :"default")
//How to get fireURL?
multipartFormData.appendBodyPart(fileURL: imageURL, name: "unicorn")
},
encodingCompletion: { encodingResult in
switch encodingResult {
case .Success(let upload, _, _):
upload.responseJSON { response in
debugPrint(response)
}
case .Failure(let encodingError):
print(encodingError)
}
}
)
What is the usual way to get NSURL for local files?
You get the UIImage instance from the picker. Take the image and write it to disk als jpg (UIImageJPEGRepresentation) or png (UIImagePNGRepresentation) and use the file URL for the store image.