I'm trying to upload an image with parameters in Swift. When I try this code, I can get the parameters but not the image
uploadFileToUrl(fotiño:UIImage){
var foto = UIImage(data: UIImageJPEGRepresentation(fotiño, 0.2))
var request = NSMutableURLRequest(URL:NSURL(string: "URL"))
request.HTTPMethod = "POST"
var bodyData = "id_user="PARAMETERS&ETC""
request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding);
request.HTTPBody = NSData.dataWithData(UIImagePNGRepresentation(foto))
println("miraqui \(request.debugDescription)")
var response: AutoreleasingUnsafeMutablePointer<NSURLResponse?>=nil
var HTTPError: NSError? = nil
var JSONError: NSError? = nil
var dataVal: NSData? = NSURLConnection.sendSynchronousRequest(request, returningResponse: response, error: &HTTPError)
if ((dataVal != nil) && (HTTPError == nil)) {
var jsonResult = NSJSONSerialization.JSONObjectWithData(dataVal!, options: NSJSONReadingOptions.MutableContainers, error: &JSONError)
if (JSONError != nil) {
println("Bad JSON")
} else {
println("Synchronous\(jsonResult)")
}
} else if (HTTPError != nil) {
println("Request failed")
} else {
println("No Data returned")
}
}
edit 2:
I think that I have some problems with the path of the saved UIImage, because php tells me that the file already exist, which I think is because I send it in blank
func createRequest (#userid: String, disco: String, id_disco: String, pub: String, foto: UIImage) -> NSURLRequest {
let param = [
"id_user" : userid,
"name_discoteca" : disco,
"id_discoteca" : id_disco,
"ispublic" : pub] // build your dictionary however appropriate
let boundary = generateBoundaryString()
let url = NSURL(string: "http....")
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.timeoutInterval = 60
request.HTTPShouldHandleCookies = false
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
var imagesaver = ImageSaver()
var image = foto // However you create/get a UIImage
let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
let destinationPath = documentsPath.stringByAppendingPathComponent("VipKing.jpg")
UIImageJPEGRepresentation(image,1.0).writeToFile(destinationPath, atomically: true)
self.saveImage(foto, withFileName: "asdasd22.jpg")
var path = self.documentsPathForFileName("asdasd22.jpg")
self.ViewImage.image = self.loadImageWithFileName("asdasd22.jpg")
// let path1 = NSBundle.mainBundle().pathForResource("asdasd22", ofType: "jpg", inDirectory: path) as String!
**//path1 always crash**
println(param.debugDescription)
println(path.debugDescription)
println(boundary.debugDescription)
request.HTTPBody = createBodyWithParameters(param, filePathKey: "asdasd22.jpg", paths: [path], boundary: boundary)
println(request.debugDescription)
return request
}
In your comment below, you inform us that you are using the $_FILES syntax to retrieve the files. That means that you want to create a multipart/form-data request. The process is basically:
Specify a boundary for your multipart/form-data request.
Specify a Content-Type of the request that specifies that it multipart/form-data and what the boundary is.
Create body of request, separating the individual components (each of the posted values as well as between each upload).
For more detail, see RFC 7578. Anyway, in Swift 3 and later, this might look like:
/// Create request
///
/// - parameter userid: The userid to be passed to web service
/// - parameter password: The password to be passed to web service
/// - parameter email: The email address to be passed to web service
///
/// - returns: The `URLRequest` that was created
func createRequest(userid: String, password: String, email: String) throws -> URLRequest {
let parameters = [
"user_id" : userid,
"email" : email,
"password" : password] // build your dictionary however appropriate
let boundary = generateBoundaryString()
let url = URL(string: "https://example.com/imageupload.php")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
let fileURL = Bundle.main.url(forResource: "image1", withExtension: "png")!
request.httpBody = try createBody(with: parameters, filePathKey: "file", urls: [fileURL], boundary: boundary)
return request
}
/// Create body of the `multipart/form-data` request
///
/// - parameter parameters: The optional dictionary containing keys and values to be passed to web service.
/// - parameter filePathKey: The optional field name to be used when uploading files. If you supply paths, you must supply filePathKey, too.
/// - parameter urls: The optional array of file URLs of the files to be uploaded.
/// - parameter boundary: The `multipart/form-data` boundary.
///
/// - returns: The `Data` of the body of the request.
private func createBody(with parameters: [String: String]? = nil, filePathKey: String, urls: [URL], boundary: String) throws -> Data {
var body = Data()
parameters?.forEach { (key, value) in
body.append("--\(boundary)\r\n")
body.append("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
body.append("\(value)\r\n")
}
for url in urls {
let filename = url.lastPathComponent
let data = try Data(contentsOf: url)
body.append("--\(boundary)\r\n")
body.append("Content-Disposition: form-data; name=\"\(filePathKey)\"; filename=\"\(filename)\"\r\n")
body.append("Content-Type: \(url.mimeType)\r\n\r\n")
body.append(data)
body.append("\r\n")
}
body.append("--\(boundary)--\r\n")
return body
}
/// Create boundary string for multipart/form-data request
///
/// - returns: The boundary string that consists of "Boundary-" followed by a UUID string.
private func generateBoundaryString() -> String {
return "Boundary-\(UUID().uuidString)"
}
With:
extension URL {
/// Mime type for the URL
///
/// Requires `import UniformTypeIdentifiers` for iOS 14 solution.
/// Requires `import MobileCoreServices` for pre-iOS 14 solution
var mimeType: String {
if #available(iOS 14.0, *) {
return UTType(filenameExtension: pathExtension)?.preferredMIMEType ?? "application/octet-stream"
} else {
guard
let identifier = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension as CFString, nil)?.takeRetainedValue(),
let mimeType = UTTypeCopyPreferredTagWithClass(identifier, kUTTagClassMIMEType)?.takeRetainedValue() as String?
else {
return "application/octet-stream"
}
return mimeType
}
}
}
extension Data {
/// Append string to Data
///
/// Rather than littering my code with calls to `data(using: .utf8)` to convert `String` values to `Data`, this wraps it in a nice convenient little extension to Data. This defaults to converting using UTF-8.
///
/// - parameter string: The string to be added to the `Data`.
mutating func append(_ string: String, using encoding: String.Encoding = .utf8) {
if let data = string.data(using: encoding) {
append(data)
}
}
}
Having all of this, you now need to submit this request. I would advise this is done asynchronously. For example, using URLSession, you would do something like:
let request: URLRequest
do {
request = try createRequest(userid: userid, password: password, email: email)
} catch {
print(error)
return
}
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
// handle error here
print(error ?? "Unknown error")
return
}
// parse `data` here, then parse it
// note, if you want to update the UI, make sure to dispatch that to the main queue, e.g.:
//
// DispatchQueue.main.async {
// // update your UI and model objects here
// }
}
task.resume()
If you are uploading large assets (e.g. videos or the like), you might want to use a file-based permutation of the above. See https://stackoverflow.com/a/70552269/1271826.
For Swift 2 renditions, see previous revision of this answer.
AlamoFire now supports Multipart:
https://github.com/Alamofire/Alamofire#uploading-multipartformdata
Here's a blog post with sample project that touches on using Multipart with AlamoFire.
http://www.thorntech.com/2015/07/4-essential-swift-networking-tools-for-working-with-rest-apis/
The relevant code might look something like this (assuming you're using AlamoFire and SwiftyJSON):
func createMultipart(image: UIImage, callback: Bool -> Void){
// use SwiftyJSON to convert a dictionary to JSON
var parameterJSON = JSON([
"id_user": "test"
])
// JSON stringify
let parameterString = parameterJSON.rawString(encoding: NSUTF8StringEncoding, options: nil)
let jsonParameterData = parameterString!.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
// convert image to binary
let imageData = UIImageJPEGRepresentation(image, 0.7)
// upload is part of AlamoFire
upload(
.POST,
URLString: "http://httpbin.org/post",
multipartFormData: { multipartFormData in
// fileData: puts it in "files"
multipartFormData.appendBodyPart(fileData: jsonParameterData!, name: "goesIntoFile", fileName: "json.txt", mimeType: "application/json")
multipartFormData.appendBodyPart(fileData: imageData, name: "file", fileName: "iosFile.jpg", mimeType: "image/jpg")
// data: puts it in "form"
multipartFormData.appendBodyPart(data: jsonParameterData!, name: "goesIntoForm")
},
encodingCompletion: { encodingResult in
switch encodingResult {
case .Success(let upload, _, _):
upload.responseJSON { request, response, data, error in
let json = JSON(data!)
println("json:: \(json)")
callback(true)
}
case .Failure(let encodingError):
callback(false)
}
}
)
}
let fotoImage = UIImage(named: "foto")
createMultipart(fotoImage!, callback: { success in
if success { }
})
Thank you #Rob, your code is working fine, but in my case, I am retriving image from gallary and taking name of the image by using code:
let filename = url.lastPathComponent
But this code, displaying image extension as .JPG (in capital letter), but server not accepting extensions in captital letter, so i changed my code as:
let filename = (path.lastPathComponent as NSString).lowercaseString
and now my code is working fine.
Thank you :)
Related
I'm trying to upload an image with parameters in Swift. When I try this code, I can get the parameters but not the image
uploadFileToUrl(fotiño:UIImage){
var foto = UIImage(data: UIImageJPEGRepresentation(fotiño, 0.2))
var request = NSMutableURLRequest(URL:NSURL(string: "URL"))
request.HTTPMethod = "POST"
var bodyData = "id_user="PARAMETERS&ETC""
request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding);
request.HTTPBody = NSData.dataWithData(UIImagePNGRepresentation(foto))
println("miraqui \(request.debugDescription)")
var response: AutoreleasingUnsafeMutablePointer<NSURLResponse?>=nil
var HTTPError: NSError? = nil
var JSONError: NSError? = nil
var dataVal: NSData? = NSURLConnection.sendSynchronousRequest(request, returningResponse: response, error: &HTTPError)
if ((dataVal != nil) && (HTTPError == nil)) {
var jsonResult = NSJSONSerialization.JSONObjectWithData(dataVal!, options: NSJSONReadingOptions.MutableContainers, error: &JSONError)
if (JSONError != nil) {
println("Bad JSON")
} else {
println("Synchronous\(jsonResult)")
}
} else if (HTTPError != nil) {
println("Request failed")
} else {
println("No Data returned")
}
}
edit 2:
I think that I have some problems with the path of the saved UIImage, because php tells me that the file already exist, which I think is because I send it in blank
func createRequest (#userid: String, disco: String, id_disco: String, pub: String, foto: UIImage) -> NSURLRequest {
let param = [
"id_user" : userid,
"name_discoteca" : disco,
"id_discoteca" : id_disco,
"ispublic" : pub] // build your dictionary however appropriate
let boundary = generateBoundaryString()
let url = NSURL(string: "http....")
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.timeoutInterval = 60
request.HTTPShouldHandleCookies = false
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
var imagesaver = ImageSaver()
var image = foto // However you create/get a UIImage
let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
let destinationPath = documentsPath.stringByAppendingPathComponent("VipKing.jpg")
UIImageJPEGRepresentation(image,1.0).writeToFile(destinationPath, atomically: true)
self.saveImage(foto, withFileName: "asdasd22.jpg")
var path = self.documentsPathForFileName("asdasd22.jpg")
self.ViewImage.image = self.loadImageWithFileName("asdasd22.jpg")
// let path1 = NSBundle.mainBundle().pathForResource("asdasd22", ofType: "jpg", inDirectory: path) as String!
**//path1 always crash**
println(param.debugDescription)
println(path.debugDescription)
println(boundary.debugDescription)
request.HTTPBody = createBodyWithParameters(param, filePathKey: "asdasd22.jpg", paths: [path], boundary: boundary)
println(request.debugDescription)
return request
}
In your comment below, you inform us that you are using the $_FILES syntax to retrieve the files. That means that you want to create a multipart/form-data request. The process is basically:
Specify a boundary for your multipart/form-data request.
Specify a Content-Type of the request that specifies that it multipart/form-data and what the boundary is.
Create body of request, separating the individual components (each of the posted values as well as between each upload).
For more detail, see RFC 7578. Anyway, in Swift 3 and later, this might look like:
/// Create request
///
/// - parameter userid: The userid to be passed to web service
/// - parameter password: The password to be passed to web service
/// - parameter email: The email address to be passed to web service
///
/// - returns: The `URLRequest` that was created
func createRequest(userid: String, password: String, email: String) throws -> URLRequest {
let parameters = [
"user_id" : userid,
"email" : email,
"password" : password] // build your dictionary however appropriate
let boundary = generateBoundaryString()
let url = URL(string: "https://example.com/imageupload.php")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
let fileURL = Bundle.main.url(forResource: "image1", withExtension: "png")!
request.httpBody = try createBody(with: parameters, filePathKey: "file", urls: [fileURL], boundary: boundary)
return request
}
/// Create body of the `multipart/form-data` request
///
/// - parameter parameters: The optional dictionary containing keys and values to be passed to web service.
/// - parameter filePathKey: The optional field name to be used when uploading files. If you supply paths, you must supply filePathKey, too.
/// - parameter urls: The optional array of file URLs of the files to be uploaded.
/// - parameter boundary: The `multipart/form-data` boundary.
///
/// - returns: The `Data` of the body of the request.
private func createBody(with parameters: [String: String]? = nil, filePathKey: String, urls: [URL], boundary: String) throws -> Data {
var body = Data()
parameters?.forEach { (key, value) in
body.append("--\(boundary)\r\n")
body.append("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
body.append("\(value)\r\n")
}
for url in urls {
let filename = url.lastPathComponent
let data = try Data(contentsOf: url)
body.append("--\(boundary)\r\n")
body.append("Content-Disposition: form-data; name=\"\(filePathKey)\"; filename=\"\(filename)\"\r\n")
body.append("Content-Type: \(url.mimeType)\r\n\r\n")
body.append(data)
body.append("\r\n")
}
body.append("--\(boundary)--\r\n")
return body
}
/// Create boundary string for multipart/form-data request
///
/// - returns: The boundary string that consists of "Boundary-" followed by a UUID string.
private func generateBoundaryString() -> String {
return "Boundary-\(UUID().uuidString)"
}
With:
extension URL {
/// Mime type for the URL
///
/// Requires `import UniformTypeIdentifiers` for iOS 14 solution.
/// Requires `import MobileCoreServices` for pre-iOS 14 solution
var mimeType: String {
if #available(iOS 14.0, *) {
return UTType(filenameExtension: pathExtension)?.preferredMIMEType ?? "application/octet-stream"
} else {
guard
let identifier = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension as CFString, nil)?.takeRetainedValue(),
let mimeType = UTTypeCopyPreferredTagWithClass(identifier, kUTTagClassMIMEType)?.takeRetainedValue() as String?
else {
return "application/octet-stream"
}
return mimeType
}
}
}
extension Data {
/// Append string to Data
///
/// Rather than littering my code with calls to `data(using: .utf8)` to convert `String` values to `Data`, this wraps it in a nice convenient little extension to Data. This defaults to converting using UTF-8.
///
/// - parameter string: The string to be added to the `Data`.
mutating func append(_ string: String, using encoding: String.Encoding = .utf8) {
if let data = string.data(using: encoding) {
append(data)
}
}
}
Having all of this, you now need to submit this request. I would advise this is done asynchronously. For example, using URLSession, you would do something like:
let request: URLRequest
do {
request = try createRequest(userid: userid, password: password, email: email)
} catch {
print(error)
return
}
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
// handle error here
print(error ?? "Unknown error")
return
}
// parse `data` here, then parse it
// note, if you want to update the UI, make sure to dispatch that to the main queue, e.g.:
//
// DispatchQueue.main.async {
// // update your UI and model objects here
// }
}
task.resume()
If you are uploading large assets (e.g. videos or the like), you might want to use a file-based permutation of the above. See https://stackoverflow.com/a/70552269/1271826.
For Swift 2 renditions, see previous revision of this answer.
AlamoFire now supports Multipart:
https://github.com/Alamofire/Alamofire#uploading-multipartformdata
Here's a blog post with sample project that touches on using Multipart with AlamoFire.
http://www.thorntech.com/2015/07/4-essential-swift-networking-tools-for-working-with-rest-apis/
The relevant code might look something like this (assuming you're using AlamoFire and SwiftyJSON):
func createMultipart(image: UIImage, callback: Bool -> Void){
// use SwiftyJSON to convert a dictionary to JSON
var parameterJSON = JSON([
"id_user": "test"
])
// JSON stringify
let parameterString = parameterJSON.rawString(encoding: NSUTF8StringEncoding, options: nil)
let jsonParameterData = parameterString!.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
// convert image to binary
let imageData = UIImageJPEGRepresentation(image, 0.7)
// upload is part of AlamoFire
upload(
.POST,
URLString: "http://httpbin.org/post",
multipartFormData: { multipartFormData in
// fileData: puts it in "files"
multipartFormData.appendBodyPart(fileData: jsonParameterData!, name: "goesIntoFile", fileName: "json.txt", mimeType: "application/json")
multipartFormData.appendBodyPart(fileData: imageData, name: "file", fileName: "iosFile.jpg", mimeType: "image/jpg")
// data: puts it in "form"
multipartFormData.appendBodyPart(data: jsonParameterData!, name: "goesIntoForm")
},
encodingCompletion: { encodingResult in
switch encodingResult {
case .Success(let upload, _, _):
upload.responseJSON { request, response, data, error in
let json = JSON(data!)
println("json:: \(json)")
callback(true)
}
case .Failure(let encodingError):
callback(false)
}
}
)
}
let fotoImage = UIImage(named: "foto")
createMultipart(fotoImage!, callback: { success in
if success { }
})
Thank you #Rob, your code is working fine, but in my case, I am retriving image from gallary and taking name of the image by using code:
let filename = url.lastPathComponent
But this code, displaying image extension as .JPG (in capital letter), but server not accepting extensions in captital letter, so i changed my code as:
let filename = (path.lastPathComponent as NSString).lowercaseString
and now my code is working fine.
Thank you :)
Below is my code referring this question answer
func createRequest(ResumeID: String, CandidateID: String, MediaName: String, FileExtension : String, MediaType : String) throws -> URLRequest {
let parameters = NSDictionary(objects: [ResumeID, CandidateID, MediaName, FileExtension,MediaType], forKeys: ["ResumeID" as NSCopying, "CandidateID" as NSCopying, "MediaName" as NSCopying, "FileExtension" as NSCopying, "MediaType" as NSCopying])
let boundary = generateBoundaryString()
let url = URL(string: "http://192.168.1.29/ColorsKit_New_Svr/WTCSvr.svc/WTCService?Id=6&SPName=Usp_RTN_IU_CandidateSubmissionResume")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
let path1 = Bundle.main.path(forResource: "dummy-pdf_2", ofType: "pdf")!
request.httpBody = try createBody(with: parameters as? [String : String], filePathKey: "MediaContent", paths: [path1], boundary: boundary)
return request
}
private func createBody(with parameters: [String: String]?, filePathKey: String, paths: [String], boundary: String) throws -> Data {
var body = Data()
if parameters != nil {
for (key, value) in parameters! {
body.append("--\(boundary)\r\n")
body.append("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
body.append("\(value)\r\n")
}
}
for path in paths {
let url = URL(fileURLWithPath: path)
let filename = url.lastPathComponent
let data = try Data(contentsOf: url)
let mimetype = mimeType(for: path)
body.append("--\(boundary)\r\n")
body.append("Content-Disposition: form-data; name=\"\(filePathKey)\"; filename=\"\(filename)\"\r\n")
body.append("Content-Type: \(mimetype)\r\n\r\n")
body.append(data)
body.append("\r\n")
}
body.append("--\(boundary)--\r\n")
return body
}
func sendMultipartRequest() {
let request: URLRequest
do {
request = try createRequest(ResumeID: "1", CandidateID: "1241124", MediaName: "dummy-pdf", FileExtension: "pdf", MediaType: "pdf")
} catch {
print(error)
return
}
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard error == nil else {
// handle error here
print(error!)
return
}
// if response was JSON, then parse it
do {
let responseDictionary = try JSONSerialization.jsonObject(with: data!)
print("success == \(responseDictionary)")
// note, if you want to update the UI, make sure to dispatch that to the main queue, e.g.:
//
// DispatchQueue.main.async {
// // update your UI and model objects here
// }
} catch {
print(error)
let responseString = String(data: data!, encoding: .utf8)
print("responseString = \(String(describing: responseString))")
}
}
task.resume()
}
The Response I'm getting is:
Error Domain=NSCocoaErrorDomain Code=3840 "JSON text did not start
with array or object and option to allow fragments not set."
UserInfo={NSDebugDescription=JSON text did not start with array or
object and option to allow fragments not set.} responseString =
Optional("No Records Found")
This is strange because Postman is giving correct response. Means there is something missing in the code only :(
Use Alamofire
let upload_url = "your url"
let fieldName = "UploadedFile"
let mimeType = "plain/text"
Alamofire.upload(multipartFormData: { multipartFormData in
//you can add multiple file
multipartFormData.append(fileData as Data, withName: fieldName, fileName: fileName, mimeType: mimeType)
}, 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 _ = self else {
return
}
debugPrint(response)
}
case .failure(let encodingError):
debugPrint("uploaderService error:\(encodingError)")
}
})
Use JSONSerialization as below
if let responseDictionary = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? String {
...
}
I'm trying to figure out how to send a photo from an iPhone to my web server.
I also need to send parameters containing the size of the photo, it's filename and other additional information about the photo in the same request as the parameter data.
The code below is on the right track I think, but where do I put the parameter data called params:
let params: Array<String> = [aI.filename, String(aI.size), String(aI.dateTime.year), String(aI.dateTime.month), String(aI.dateTime.day), String(aI.dateTime.hour), String(aI.dateTime.minute), String(aI.dateTime.second), String(aI.dateTime.millisecond)]
var serverURL = URL(string: "http://192.168.0.23/upload.php");
var req = NSMutableURLRequest(url: serverURL!, cachePolicy: NSURLRequest.CachePolicy.useProtocolCachePolicy, timeoutInterval: 60.0);
//Set request to post
req.httpMethod = "POST";
//Set content type
req.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type");
let task = URLSession.sharedSession().dataTaskWithRequest(req){ data, response, error in
if error != nil{
print("Error -> \(error)")
return
}
do {
let result = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? [String:AnyObject]
print("Result -> \(result)")
} catch {
print("Error -> \(error)")
}
}
task.resume()
return task
Allthough some of the answers pushed me in the right direction, they still didn't fit my project and so I continued googling an I managed to find exactly what I needed in the following article: http://swiftdeveloperblog.com/image-upload-example/
I needed to make the HTTP request asynchronously and using sessions,
which I didn't specify in the question because the question was merely about how to send both several parameters along with data in one single request.
It is called Multipart Form Data when doing so.
I had to modify the code from the article a little bit to make it work for my application,
so I'm sharing my Swift 3 code below:
Trigger code
let params = [
"filename" : chunkOwner.filename ,
"size" : String(describing: chunkOwner.size) ,
"year" : String(chunkOwner.dateTime.year) ,
"month" : String(chunkOwner.dateTime.month) ,
"day" : String(chunkOwner.dateTime.day) ,
"hour" : String(chunkOwner.dateTime.hour) ,
"minute" : String(chunkOwner.dateTime.minute) ,
"second" : String(chunkOwner.dateTime.second) ,
"millisecond" : String(chunkOwner.dateTime.millisecond) ,
]
uploadChunk(url: URL(string: "http://192.168.0.23/upload.php")!, data: photoData, params: params)
Upload code:
func uploadData(url: URL, data: Data!, params: [String: String])
{
let cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringLocalCacheData;
let request = NSMutableURLRequest(url: url, cachePolicy: cachePolicy, timeoutInterval: 6.0);
request.httpMethod = "POST";
let boundary = generateBoundaryString()
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
if(data == nil) { return; }
request.httpBody = createBodyWithParameters(parameters: params, filePathKey: "file", data: data, boundary: boundary)
//myActivityIndicator.startAnimating();
let task = URLSession.shared.dataTask(with: request as URLRequest) {
data, response, error in
if error != nil {
print("error=\(error)")
return
}
// You can print out response object
print("******* response = \(response)")
// Print out reponse body
let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
print("****** response data = \(responseString!)")
do {
let json = try JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary
print(json)
}catch
{
//if you recieve an error saying that the data could not be uploaded,
//make sure that the upload size is set to something higher than the size
print(error)
}
}
task.resume()
}
func createBodyWithParameters(parameters: [String: String]?, filePathKey: String?, data: Data!, boundary: String) -> Data {
var body = Data();
if parameters != nil {
for (key, value) in parameters! {
body.appendString(string: "--\(boundary)\r\n")
body.appendString(string: "Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
body.appendString(string: "\(value)\r\n")
}
}
let mimetype = "text/csv"
body.appendString(string: "--\(boundary)\r\n")
body.appendString(string: "Content-Disposition: form-data; name=\"\(filePathKey!)\"; filename=\"\(parameters!["filename"]!)\"\r\n")
body.appendString(string: "Content-Type: \(mimetype)\r\n\r\n")
body.append(data)
body.appendString(string: "\r\n")
body.appendString(string: "--\(boundary)--\r\n")
return body
}
func generateBoundaryString() -> String {
return "Boundary-\(NSUUID().uuidString)"
}
Also include the following code at the bottom of your .swift file outside of your class:
extension Data {
mutating func appendString(string: String) {
append(string.data(using: .utf8)!)
}
}
And for the PHP upload script I did some changes and now looks like this:
<?php
$target_dir = "/var/www/html/uploads";if(!file_exists($target_dir)){
mkdir($target_dir, 0777, true);
}
$target_dir = $target_dir . "/" . basename($_FILES["file"]["name"]);
echo count("size: ".$_FILES["file"]["tmp_name"]);
if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_dir)){
echo json_encode([
"Message" => "The file ". basename( $_FILES["file"]["name"]). " has been uploaded.",
"Status" => "OK",
]);
} else {
echo json_encode([
"Message" => "Sorry, there was an error uploading your file.",
"Status" => "Error",
]);
}
?>
Important Note:
Your app will fail to upload data if your server php file called
php.ini is configured to accept files smaller than the data you're
trying to upload.
For example: If php.ini is configured to accept 2 MB, then any
uploads larger than 2 MB will be ignored and your app will receive a
response saying that something went wrong.
To change the file size acceptance in php.ini you need to look for
the variable called upload_max_filesize and post_max_sizeand change those to whatever file size
your system requires.
You can put them to httpBody or to httpBodyStream (by using NSInputStream)
But don't forget to transform params for server protocol (for example xml, json, or binary data with custom format).
For your content type (application/x-www-form-urlencoded), you can find format in wikipedia:
keyName=value&keyName2=value2
The keys and values should contain of URLPathAllowedCharacterSet, to achieve it you can use stringByAddingPercentEncodingWithAllowedCharacters.
To convert the KeyValue string to NSData, you can use method dataUsingEncoding.
I am sharing you one way of posting data using NSURLConnection in Swift3
Your URL
var serverURL = URL(string: "http://192.168.0.23/upload.php")
Your parameters to be like this , just discuss with server people to which parameters you to need pass data Then assign your value to that parameter like below
serverparameter1 = \(value to post)& serverparameter2 = \(value to post2).......
With your params I did like this have a look
let params = "filename= \(aI.filename)&size = \(String(aI.size))& dateTimeYear =\(String(aI.dateTime.year))&dateTimeMonth =\(String(aI.dateTime.month))& dateTimeDay =\(String(aI.dateTime.day))&dateTimeHour =\(String(aI.dateTime.hour))&dateTimeMinute =\(String(aI.dateTime.minute))&dateTimeSecond =\(String(aI.dateTime.second))&dateTimeMilliSecond=\(String(aI.dateTime.millisecond))"
Convert your Photo Data to Base64String like below
var base64String: NSString!
let myImage = UIImage(named:"image.png")
let imageData = UIImageJPEGRepresentation(myImage, 0.9)
base64String = imageData!.base64EncodedString(options: NSData.Base64EncodingOptions.endLineWithLineFeed) as NSString!
print(base64String)
then pass as stringParameter
&ImageDataStr = \(base64String)
then final Url seems to be look like
\(serverURL)/\(params)
OR
\(serverURL)/Upload?\(params)
Step by step request
var serverURL = URL(string: "http://192.168.0.23/upload.php")
let params = "filename= \(aI.filename)&size = \(String(aI.size))& dateTimeYear =\(String(aI.dateTime.year))&dateTimeMonth =\(String(aI.dateTime.month))& dateTimeDay =\(String(aI.dateTime.day))&dateTimeHour =\(String(aI.dateTime.hour))&dateTimeMinute =\(String(aI.dateTime.minute))&dateTimeSecond =\(String(aI.dateTime.second))&dateTimeMilliSecond=\(String(aI.dateTime.millisecond))&photoDataStr = \(base64String)"
var status:NSString = "\(serverURL)/Upload?\(params)" as NSString
status = status.addingPercentEscapes(using: String.Encoding.utf8.rawValue)! as NSString
let url = URL(string: status as String)!
let request = URLRequest(url: url, cachePolicy:NSURLRequest.CachePolicy.reloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 600)
// need synchronous
Here you will get responseData
var response:URLResponse?
var responseD:Data = try! NSURLConnection.sendSynchronousRequest(request, returning:&response)
Finally make that BinaryData to readable
// save to string - the result came from the Server call
var serverResults:NSString = NSString(data: responseD, encoding: String.Encoding.utf8.rawValue)!
print(serverResults)
For Example your Result
if serverResults.range(of: "RESULT>APPROVED").location != NSNotFound
{
return "Data posted"
}
else
{
return "Failed to post"
}
I am trying to upload an image, and a text file(uploading it as Data).
So far I can upload the image alone correctly, and also upload the text file data uploading it as a .txt successfully alone.
Now I need to upload both image and .txt file together...
I am not sure how to set the Paramaters up in my IOS app for this....
So far this is how I upload the .txt file (basically the same way I upload the image but I change the "filename" and "mimetype")
func createBodyWithParameters(parameters: [String : Any]?, filePathKey: String?,filePathKey1: String?, imageDataKey: NSData,imageDataKey1: NSData, boundary: String) -> NSData {
let body = NSMutableData();
if parameters != nil {
for (key, value) in parameters! {
body.appendString("--\(boundary)\r\n")
body.appendString("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
body.appendString("\(value)\r\n")
}
}
let filename = "post-\(uuid).txt"
let mimetype = "image/txt"
body.appendString("--\(boundary)\r\n")
body.appendString("Content-Disposition: form-data; name=\"\(filePathKey!)\"; filename=\"\(filename)\"\r\n")
body.appendString("Content-Type: \(mimetype)\r\n\r\n")
body.append(imageDataKey as Data)
body.appendString("\r\n")
body.appendString("--\(boundary)--\r\n")
return body
}
Now I am not sure how to save both image and .txt file with that paramater.
This however is the rest of my swift code for uploading it:
let param = [
"id" : id,
"uuid" : uuid,
"Text" : Text,
"Title" : Title
] as [String : Any]
let boundary = "Boundary-\(NSUUID().uuidString)"
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
let data: Data = NSKeyedArchiver.archivedData(withRootObject: blogattributedText)
var imageData = NSData()
let image = CoverImage
let width = CGSize(width: self.view.frame.width, height: image.size.height * (self.view.frame.width / image.size.width))
imageData = UIImageJPEGRepresentation(imageWithImage(image, scaledToSize: width), 0.5)! as NSData
// ... body
request.httpBody = createBodyWithParameters(parameters: param, filePathKey: "file",filePathKey1: "file1", imageDataKey: data as NSData,imageDataKey1: imageData as NSData, boundary: boundary) as Data
If anyone needs to see anymore of my code or doesn't understand my question please let me know!
Thanks in advance to anyone that can help!!
If you don't want to get lost in the weeds of creating complex requests, a third party library like Alamofire would be smart. It's by the same author as AFNetworking, but it's a native Swift library.
So, an Alamofire implementation might look like:
func performRequest(urlString: String, id: String, uuid: String, text: String, title: String, blogAttributedText: NSAttributedString, image: UIImage) {
let parameters = [
"id" : id,
"uuid" : uuid,
"Text" : text,
"Title" : title
]
let imageData = UIImageJPEGRepresentation(image, 0.5)!
let blogData = NSKeyedArchiver.archivedData(withRootObject: blogAttributedText)
Alamofire.upload(
multipartFormData: { multipartFormData in
for (key, value) in parameters {
if let data = value.data(using: .utf8) {
multipartFormData.append(data, withName: key)
}
}
multipartFormData.append(imageData, withName: "image", fileName: "image.jpg", mimeType: "image/jpeg")
multipartFormData.append(blogData, withName: "blog", fileName: "blog.archive", mimeType: "application/octet-stream")
},
to: urlString,
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload
.validate()
.responseJSON { response in
switch response.result {
case .success(let value):
print("responseObject: \(value)")
case .failure(let responseError):
print("responseError: \(responseError)")
}
}
case .failure(let encodingError):
print("encodingError: \(encodingError)")
}
})
}
If you're going to build this request yourself, I'd suggest a few things. First, since you're sending files of different types, you might want some nice type to encapsulate this:
struct FilePayload {
let fieldname: String
let filename: String
let mimetype: String
let payload: Data
}
I'm also not sure what to make of the image/txt mime type. I'd probably use application/octet-stream for the archive.
Anyway, the building of the request could be as follows:
/// Create request.
///
/// - Parameters:
/// - url: The URL to where the post will be sent.
/// - id: The identifier of the entry
/// - uuid: The UUID of the entry
/// - text: The text.
/// - title: The title.
/// - blogAttributedText: The attributed text of the blog entry.
/// - image: The `UIImage` of the image to be included.
///
/// - Returns: The `URLRequest` that was created
func createRequest(url: URL, id: String, uuid: String, text: String, title: String, blogAttributedText: NSAttributedString, image: UIImage) -> URLRequest {
let parameters = [
"id" : id,
"uuid" : uuid,
"Text" : text, // I find it curious to see uppercase field names (I'd use lowercase for consistency's sake, but use whatever your PHP is looking for)
"Title" : title
]
let boundary = "Boundary-\(NSUUID().uuidString)"
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept") // adjust if your response is not JSON
// use whatever field name your PHP is looking for the image; I used `image`
let imageData = UIImageJPEGRepresentation(image, 0.5)!
let imagePayload = FilePayload(fieldname: "image", filename: "image.jpg", mimetype: "image/jpeg", payload: imageData)
// again, use whatever field name your PHP is looking for the image; I used `blog`
let blogData = NSKeyedArchiver.archivedData(withRootObject: blogAttributedText)
let blogPayload = FilePayload(fieldname: "blog", filename: "blog.archive", mimetype: "application/octet-stream", payload: blogData)
request.httpBody = createBody(with: parameters, files: [imagePayload, blogPayload], boundary: boundary)
return request
}
/// Create body of the multipart/form-data request.
///
/// - Parameters:
/// - parameters: The optional dictionary containing keys and values to be passed to web service.
/// - files: The list of files to be included in the request.
/// - boundary: The `multipart/form-data` boundary
///
/// - Returns: The `Data` of the body of the request.
private func createBody(with parameters: [String: String]?, files: [FilePayload], boundary: String) -> Data {
var body = Data()
if parameters != nil {
for (key, value) in parameters! {
body.append("--\(boundary)\r\n")
body.append("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
body.append("\(value)\r\n")
}
}
for file in files {
body.append("--\(boundary)\r\n")
body.append("Content-Disposition: form-data; name=\"\(file.fieldname)\"; filename=\"\(file.filename)\"\r\n")
body.append("Content-Type: \(file.mimetype)\r\n\r\n")
body.append(file.payload)
body.append("\r\n")
}
body.append("--\(boundary)--\r\n")
return body
}
/// Create boundary string for multipart/form-data request
///
/// - returns: The boundary string that consists of "Boundary-" followed by a UUID string.
private func generateBoundaryString() -> String {
return "Boundary-\(NSUUID().uuidString)"
}
Where
extension Data {
/// Append string to Data
///
/// Rather than littering my code with calls to `dataUsingEncoding` to convert strings to `Data`, and then add that data to the `Data`, this wraps it in a nice convenient little `Data` extension. This converts using UTF-8.
///
/// - parameter string: The string to be added to the mutable `Data`.
mutating func append(_ string: String) {
if let data = string.data(using: .utf8) {
append(data)
}
}
}
Clearly this was Swift 3 code, so I excised the NSMutableData reference.
Alternatively, you can make JSON rest API's.
Convert your notepad file content in Base64 encoded string.
Convert your image file in Base64 encoded string.
Pass both Base64 encoded string in request parameters.
Once you get Base64 encoded string on API file in function parameter.
Again decode Base64 string and store it in content folder.
https://github.com/AFNetworking/AFNetworking/wiki/Getting-Started-with-AFNetworking
upload image using AFNetworking in swift ios
Uploading image with AFNetworking 2.0
Note - Show image on iOS app, you can make absolute URL and using image caching class you can display image.
The following curl works
curl -G -H "api_key: MYAPIKEY" https://api.semantics3.com/test/v1/products -d 'q={"upc":"70411576937"}'
However, upon trying to convert it to iOS I get the following error:
Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost." {NSErrorFailingURLStringKey=https://api.semantics3.com/test/v1/products,...}
I have attached my code below but I believe that my problem is the "q=" right before the json data that is being submitted to the URL. If so, what is this called and how do I put "q=" before my json data? I can't exactly tell though, due to iOS' unfaltering ability to provide us with unrelated error messages. Thank you.
var urlString = "https://api.semantics3.com/test/v1/products"
var request = NSMutableURLRequest(URL: NSURL(string: urlString)!)
var response: NSURLResponse?
var error: NSErrorPointer = nil
var reqText = ["upc": "70411576937"]
var err: NSError?
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(reqText, options: nil, error: &err)
request.HTTPMethod = "GET"
request.addValue("MYAPIKEY", forHTTPHeaderField: "api_key")
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
var session = NSURLSession.sharedSession()
var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
var strData = NSString(data: data, encoding: NSUTF8StringEncoding)
if(err != nil) {
println(err!.localizedDescription)
}
else {
//this is where the error is printed
println(error)
var parseError : NSError?
// parse data
let unparsedArray: AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments, error: &parseError)
println(parseError)
if let resp = unparsedArray as? NSDictionary {
println(resp)
}
}
})
task.resume()
Body is not used in GET http methods. Use the following code to concat your params:
extension String {
/// Percent escape value to be added to a URL query value as specified in RFC 3986
///
/// This percent-escapes all characters besize the alphanumeric character set and "-", ".", "_", and "~".
///
/// http://www.ietf.org/rfc/rfc3986.txt
///
/// :returns: Return precent escaped string.
func stringByAddingPercentEncodingForURLQueryValue() -> String? {
let characterSet = NSMutableCharacterSet.alphanumericCharacterSet()
characterSet.addCharactersInString("-._~")
return self.stringByAddingPercentEncodingWithAllowedCharacters(characterSet)
}
}
extension Dictionary {
/// Build string representation of HTTP parameter dictionary of keys and objects
///
/// This percent escapes in compliance with RFC 3986
///
/// http://www.ietf.org/rfc/rfc3986.txt
///
/// :returns: String representation in the form of key1=value1&key2=value2 where the keys and values are percent escaped
func stringFromHttpParameters() -> String {
let parameterArray = map(self) { (key, value) -> String in
let percentEscapedKey = (key as! String).stringByAddingPercentEncodingForURLQueryValue()!
let percentEscapedValue = (value as! String).stringByAddingPercentEncodingForURLQueryValue()!
return "\(percentEscapedKey)=\(percentEscapedValue)"
}
return join("&", parameterArray)
}
}
var urlString = "https://api.semantics3.com/test/v1/products"
var reqText = ["upc": "70411576937"]
var err: NSError?
let parameterString = reqText.stringFromHttpParameters()
let requestURL = NSURL(string:"\(urlString)?\(parameterString)")!
var request = NSMutableURLRequest(URL: NSURL(string: urlString)!)
var response: NSURLResponse?
var error: NSError?
request.HTTPMethod = "GET"
request.addValue("MYAPIKEY", forHTTPHeaderField: "api_key")
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
var session = NSURLSession.sharedSession()
PARTIAL EDIT: SWIFT 2.1 (updated)
extension Dictionary {
func stringFromHttpParameters() -> String {
let parameterArray = self.map { (key, value) -> String in
let percentEscapedKey = (key as! String).stringByAddingPercentEncodingForURLQueryValue()!
let percentEscapedValue = (value as! String).stringByAddingPercentEncodingForURLQueryValue()!
return "\(percentEscapedKey)=\(percentEscapedValue)"
}
return parameterArray.joinWithSeparator("&")
}
}
Convert your JSON to a string, prepend the q= to this, then convert the resulting string to Data before assigning it to the request's HTTPBody.
Something like this perhaps:
let array = [ "one", "two" ]
let data = NSJSONSerialization.dataWithJSONObject(array, options: nil, error: nil)
let body= "q=" + NSString(data: data!, encoding: NSUTF8StringEncoding)
request.HTTPBody = body.dataUsingEncoding(NSUTF8StringEncoding)