Upload of data not populating $_FILES - swift

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
...
}

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")

Alamofire photo upload with key of the file in body

I am able to upload a photo via Postman but in my iOS application it fails, and it is so weird that I still get a .success from encodingCompletion.
Here is part of my code
UpdateUserInfo
//
// Update user info
//
func updateUserInfo(){
var imageData: Data!
var url = ""
if let userId = KeychainWrapper.standard.string(forKey: USER_ID_KEY){
url = URL_USER_UPLOAD_PIC + userId
}
if pickedImage != nil{
imageData = UIImagePNGRepresentation(pickedImage)
//imageData = UIImageJPEGRepresentation(pickedImage!, 1.0)
}
let token = KeychainWrapper.standard.string(forKey: USER_LOGIN_TOKEN_KEY)!
let headers: HTTPHeaders = [
"Authorization": "Bearer \(token)"
]
if imageData != nil{
Alamofire.upload(multipartFormData: { (multipartFormData) in
multipartFormData.append(imageData!, withName: "fileset", fileName: "file.png", mimeType: "image/png")
}, to: url,
method: .post,
headers: headers,
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
print("Donkey Success \(String(describing: upload.response?.statusCode))")
upload.responseString(completionHandler: { (response) in
debugPrint(response)
})
case .failure(let encodingError):
print(encodingError)
print("Donkey Fail")
}
})
}
}
and in my postman I have
Postman
My first question is why I am getting a .success if it fails to upload?
and my second question is, do I need to put the key "pic" (seen in Postman) somewhere in my request? if so where?
Thanks for any help in advance
In Post man Image Key is pic but in your code its "fileset"
change to
multipartFormData.append(imageData!, withName: "pic", fileName: "file.png", mimeType: "image/png")
And success is Result of encoding not uploading processs
EncodingResult is MultipartFormDataEncodingResult that Defines
whether the MultipartFormData encoding was successful and contains
result of the encoding as associated values. - Success: Represents a successful MultipartFormData encoding and contains the
new UploadRequest along with
streaming information. - Failure: Used to represent a failure in the MultipartFormData encoding and also
contains the encoding

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)
}
})

Upload audio binary file using Alamofire

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)
}
}
)

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.