Alamofire MultiPartForm files in NSTemporaryDirectory - ios

I have not been able to find answer to my question anywhere so I figured I've ask.
I am using Alamofire 3.1.5 for uploading rather large volume of pictures, we are talking in hundreds of MB.
There is a code snippet:
self.manager.upload(.POST, url, headers: headers, multipartFormData: { multipartFormData in
multipartFormData.appendBodyPart(fileURL: generalURL, name: "general", fileName: "general", mimeType: "image/jpeg")
multipartFormData.appendBodyPart(fileURL: img1URL, name: "img1", fileName: "img1", mimeType: "image/jpeg")
multipartFormData.appendBodyPart(fileURL: img2URL, name: "img2", fileName: "img2", mimeType: "image/jpeg")
multipartFormData.appendBodyPart(fileURL: img3URL, name: "img3", fileName: "img3", mimeType: "image/jpeg")
}, encodingCompletion: { encodingResult in
.
.
.
As I understand Alamofire handles creating those request by saving them to disk, for better RAM optimalization. Which is smart and I am really happy about it. It just work flawless.
On the other hand that means that it is basically doubling the data payload on disk.
The things is that those files a are not getting deleted, It even causes iOS default screen warning that the device is running low on free space.
I know how to delete content of this directory, but in my current code flow it is safe to delete the content after all the request are finished, it may be even 100 requests, and each one of them takes roughly 20MB of payload. So the thing is that the device might not even have the capacity of storing this amount of data.
My question is:
Can I make Alamofire to delete every single one of these files after it gets successfully uploaded?
Sorry for rather long question, I would post you a potato here, but this is not 9gag.

According to this this issue, you will need to delete it yourself.
It's simple, just delete all files Alamofire generated after you get a response from server. Here's how I did it:
// Just some upload
Alamofire.upload(
.POST, uploadURL,
multipartFormData: { multipartFormData in
multipartFormData.appendBodyPart(fileURL: somePath, name: "file")
},
encodingCompletion: { encodingResult in
switch encodingResult {
case .Success(let upload, _, _):
upload.responseJSON { response in
if let JSON = response.result.value {
/*** delete temp files Alamofire generated ***/
let temporaryDirectoryPath = NSTemporaryDirectory()
let dir = NSURL(fileURLWithPath: temporaryDirectoryPath, isDirectory: true)
.URLByAppendingPathComponent("com.alamofire.manager")
.URLByAppendingPathComponent("multipart.form.data")
do {
try NSFileManager.defaultManager().removeItemAtPath(dir.path!)
} catch {}
}
}
}
)

Related

Uploading multiple images with Alamofire causes huge memory usage

I am working on an app that we need to upload multiple images to our server using Alamofire. The problem is converting UIImage to Data then appending it to Multipart uses so much memory and eventually causes app to crash.
Alamofire.upload(multipartFormData: { (multipart) in
for (key, value) in endpoint.params {
if let images = value as? [UIImage] {
for i in 0..<images.count {
if let data = UIImageJPEGRepresentation(images[i], 0.6) {
multipart.append(data, withName: "\(key)\(i)", fileName: "note.jpg", mimeType: "image/jpeg")
}
}
}
}
}, usingThreshold: UInt64.init(),
to: endpoint.path,
method: endpoint.method,
headers: endpoint.headers,
encodingCompletion: {...}
Some people advised using a stream but couldn't find an example. How can I fix the issue?

iOS Swift uploading PDF file with Alamofire (Multipart)

I'm currently developing an application using iOS 10 and Swift 3 and Alamofire 4
The purpose of this application is to upload a PDF file generated previously.
The PDF generation is working perfectly and the file is created.
However the upload doesn’t work…
I received a success response but the file is not uploaded.
My server response
Multi part Content-Type => multipart/form-data; boundary=alamofire.boundary.56958be35bdb49cb
Multi part Content-Length => 293107
Multi part Content-Boundary => alamofire.boundary.56958be35bdb49cb
responses
SUCCESS: {
uploadedFiles = (
{
details = " Key=Content-Disposition - values=[form-data; name=\"pdfDocuments\"] length=8";
storedFileName = "/var/www/pdf/17/009/22/TMP104150531290406.tmp";
type = PDF;
uploadedDate = 1483999296701;
uploadedFileName = UnknownFile;
}
);
}
end responses
I’m using multi-part to upload my file as Data as you can see here
File url is fine.
I have searched on SO but didn’t find any solution working…
Here you can see my Controller
Alamofire.upload(
multipartFormData: {
multipartFormData in
if let urlString = urlBase2 {
let pdfData = try! Data(contentsOf: urlString.asURL())
var data : Data = pdfData
multipartFormData.append(data as Data, withName:"test.pdf", 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("end responses")
onCompletion(true, "Something bad happen...", 200)
}
case .failure(let encodingError):
print(encodingError)
onCompletion(false, "Something bad happen...", 200)
}
})
Thanks in advance for the help.
Regards
I have just found my solution to fix this bug.
I have forgot a parameter for the file name.
multipartFormData.append(pdfData, withName: "pdfDocuments", fileName: namePDF, mimeType:"application/pdf")
Thanks for the help.

Alamofire 4.0 / Swift 3.0 - Appending multipart form data (CSV file)

I previously had a .post multiform upload working in Swift 2.2, which followed the following format (note that I'm not including all of the AlamoFire code...that would be too lengthy. I'm just including the relevant portions):
let data = mailStringArray[i].dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
csvDataArray.append(data!)
self.alamoFireManager.upload(.POST, "INSERT URL HERE", headers: header, multipartFormData: { multipartFormData in
multipartFormData.appendBodyPart(data: csvDataArray[0], name: "bulk", fileName: "multi-input.csv", mimeType: "text/csv")
This worked perfectly. However, after migrating to Swift 3.0 and Alamofire 4.0, I'm now using the following format:
let data = String(mailStringArray[i]).data(using: String.Encoding.utf8, allowLossyConversion: false)
csvDataArray.append(data! as NSData)
self.alamoFireManager.upload(multipartFormData:{ multipartFormData in
multipartFormData.append(csvDataArray[0], withName: "bulk", fileName: "multi-input.csv", mimeType: "text/csv")
usingThreshold:UInt64.init(),
to:"INSERT URL HERE",
method:.post,
headers:["Authorization": "INSERT TOKEN HERE"],
encodingCompletion: { encodingResult in
I end up getting the following error: Cannot invoke argument append with an argument list of type '(NSData, withName: String, fileName: String, mimeType: String)'
I'm thinking its because in Swift 3.0 i can no longer post NSData with a mimetype of "text/csv"....but I'm not entirely sure.
Any help would be great. Thanks!
Try
multipartFormData.append(csvDataArray[0] as Data, withName: "bulk", fileName: "multi-input.csv", mimeType: "text/csv")

iOS Swift + Alamofire upload photos with exif data

I am using Alamofire to upload multiple files at the same time to Open Asset using their REST API and I am able to get this to work, however, most of the EXIF data is being stripped out. Unfortunately, the EXIF data is a must as we need the ability mine out the GPS tags and a few other things through various web clients.
After doing some research, I found the issue is because I'm using UIImageJPEGRepresentation to convert the photos to NSData (which is what Alamofire expects or a fileURL, which I don't think would work for me?).
I am also using the BSImagePicker library to allow the user to take/select multiple photos, which returns a an array of PHAssets which then get converted to NSData. Here is my function to do this (where collectedImages is a global dictionary):
func compressPhotos(assets: [PHAsset]) -> Void {
for asset in assets {
let filename = self.getOriginalFilename(asset)
let assetImage = self.getAssetPhoto(asset)
let compressedImage = UIImageJPEGRepresentation(assetImage, 0.5)! // bye bye metadata :(
collectedImages[filename] = compressedImage
print("compressed image: \(filename)")
}
}
I think I could retain the EXIF data if I could use the full path from the PHAsset to the image locally on the phone, but Alamofire does not appear to support that. I'm hoping I'm wrong about that. Here is my uploader:
func uploadPhotos(projectId: String, categoryId: String, data: [String: NSData], completionHandler: (AnyObject?, NSError?) -> ()) {
var jsonBody = [AnyObject]() //lazy
Alamofire.upload(
.POST,
self.url + "/Files",
multipartFormData: { multipartFormData in
for (filename, img) in data {
jsonBody.append(["project_id": projectId, "category_id": categoryId, "original_filename": filename])
multipartFormData.appendBodyPart(data: img, name: "file", fileName: filename, mimeType: "image/jpeg")
print("img size: \(img.length)")
}
let jsonData = jsonToNSData(jsonBody)
print("_jsonBody: \(jsonBody)")
multipartFormData.appendBodyPart(data: jsonData!, name: "_jsonBody")
print("multipart: \(multipartFormData)")
},
encodingCompletion: { encodingResult in
switch encodingResult {
case .Success(let upload, _, _):
upload.responseJSON { response in
debugPrint(response)
switch response.result {
case .Success(let value):
completionHandler(value as? NSArray, nil)
case .Failure(let error):
completionHandler(nil, error)
}
}
case .Failure(let encodingError):
print(encodingError)
}
}
)
}
So my question is, how can I upload multiple photos (while passing in other parameters too) while maintaining all the EXIF data? Alamofire is an awesome library and I would like to use it here, but I'm not married to it for the upload process if I can't keep the EXIF data.
I think you can first get the file URL from the PHAsset then use that file URL in the call to multipartFormData.appendBodyPart(...). Something like this:
Get URL from PHAsset:
[asset requestContentEditingInputWithOptions:editOptions
completionHandler:^(PHContentEditingInput *contentEditingInput, NSDictionary *info) {
NSURL *imageURL = contentEditingInput.fullSizeImageURL;
}];
Use file URL in AlamoFire API:
multipartFormData.appendBodyPart(fileURL: imageURL, name: "image")
I am not sure why I was having issues with the fullSizeImageURL, but I it did lead me to the right path as I was able to get this to work by getting the image as NSData from the file path like this:
asset.requestContentEditingInputWithOptions(PHContentEditingInputRequestOptions()) { (input, _) in
let fileURL = input!.fullSizeImageURL?.filePathURL
let data = NSData(contentsOfFile: fileURL!.path!)!
And then I just passed that in the Alamofire.request() as the data argument. This maintained all the original photo metadata.

Using Alamofire and multipart/form-data

I'm unable to approach the API that has been offered to me in the proper way for it to give me the response I'm looking for. I've been using Swift and Alamofire for a while but this is the first time I've to upload images using multipart/form-data. I'm able to upload images using Postman but I'm unable to get the same message send out by my application using the Alamofire framework.
My Swift code:
func postFulfilWish(wish_id: Int, picture : UIImage, completionHandler: ((AnyObject?, ErrorType?) -> Void)) {
var urlPostFulfilWish = Constant.apiUrl;
urlPostFulfilWish += "/wishes/";
urlPostFulfilWish += String(wish_id);
urlPostFulfilWish += "/fulfill/images" ;
let image : NSData = UIImagePNGRepresentation(UIImage(named: "location.png")!)!
Alamofire.upload(.POST, urlPostFulfilWish, headers: Constant.headers, multipartFormData: { multipartFormData in
multipartFormData.appendBodyPart(data: image, name: "file")
},
encodingCompletion: { encodingResult in
switch encodingResult {
case .Success(let upload, _, _):
upload.responseJSON { response in
//This is where the code ends up now
//So it's able to encode my message into multipart/form-data but it's not doing it in the correct way for the API to handle it
debugPrint(response)
}
case .Failure(let encodingError):
print(encodingError)
}
}
)
}
In case it is not already answered, recently I had the same problem using Alamofire to upload an Image using form-data.
I was able to upload the image using Postman exactly as it's shown in this post, but no able to do it using Alamofire in my app.
You need to check two things, first of all, the name of the file that the server is expecting, and second the method used to append the body part in the multipartFormData closure.
This two methods were not working in my case -
multipartFormData.appendBodyPart(data: imageData, name: "file")
this one neither
multipartFormData.appendBodyPart(data: imageData, name: "file", fileName: name)
But on this one worked splendid -
multipartFormData.appendBodyPart(data: imageData, name: "file", fileName: "file.jpeg", mimeType: "image/jpeg")
The problem basically is that the server can't find the file with the expected name.
I hope this help someone to save time wondering why it's not working.
You are doing debugPrint(response). You presumably should do another switch response.result { ... } and see if you got .Success or .Failure as the result of the request, and if success, you'd look at the response object contents (or if failure, look at the failure error). You need to look at that result to diagnose whether it was successful or not.
Alamofire.upload(.POST, urlPostFulfilWish, headers: Constant.headers, multipartFormData: { multipartFormData in
multipartFormData.appendBodyPart(data: image, name: "file")
}) { encodingResult in
switch encodingResult {
case .Success(let upload, _, _):
upload.responseJSON { response in
switch response.result {
case .Success(let value):
print(value)
case .Failure(let error):
print(error)
}
}
case .Failure(let encodingError):
print(encodingError)
}
}
I recently got a 404 from the server when posting a multipart request along with parameters in the body. I was using a UIImagePickerController (the delegate for which returns a UIImage) and I then sent up the PNG representation of it.
This only occurred for files that were JPEG on disk. Strangely this issue seems to only affect multipart requests that also had parameters in the body. It worked fine when the API endpoint didn't require anything else.
My guess is that there is something weird going on along the line of JPEG -> UIImage -> PNG representation that results in some sort of problem which oddly only seems to manifest itself in multipart requests that also have parameters in the body. Might be some special characters in there that makes the server not recognise the request and just return a 404.
I ended up fixing it by sending up the UIImageJPEGRepresentation of the selected image instead of UIImagePNGRepresentation, and no such errors.
I believe the question is outdated already but for as long as there is no answer accepted try the following:
multipartFormData.appendBodyPart(data: imageData, name: "name", fileName: "filename", mimeType: mimeType)

Resources