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.
Related
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")
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)
}
})
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)
}
}
)
I've been experiencing some issues to upload a file to a server using Alamofire.
The files are uploaded well, but the variables where the upload should appear are empty : FILES:array(0) {\n}\nPOST:array(0) {\n}\n
And using the website, we can upload images without any problem
Would anyone have an explanation or a solution to my problem?
(the file size is not an issue, I send a 370kb image and the limit is 20mb)
func postImages(images : [UIImage], compression : CGFloat, completion: ((AnyObject?)->())? = nil) {
AlamoNoCache.manager?.upload(.POST,
"\(MYURL)/upload?access_token=" + "youwontknowit",
multipartFormData: {
multipartFormData in
for (index, image) in images.enumerate() {
multipartFormData.appendBodyPart(data: UIImageJPEGRepresentation(image, compression)!, name: "file", mimeType: "image/jpeg")
}
}, encodingCompletion: {
encodingResult in
switch encodingResult {
case .Success(let upload, let streamingFromDisk, let streamFileURL):
print(upload)
print(streamingFromDisk)
print(streamFileURL)
upload
.progress({
a, b, c in
print("\(a), \(b), \(c)")
})
.responseString(completionHandler: {
a in
print("\(a)")
}
)
break
case .Failure(let error):
print(error)
break
}
})
}
Thank you for your time.
I used this with Alamofire for upload any kind of files:
let request = alamofireManager.upload(.POST, remoteURL, headers: httpHeaders, file: fileUrl);
and if you want to handle the response:
request.response {(request, response, object, error) -> Void in
...
}
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)
}
}
)
}