ios - MYSQL and Swift - Upload image and FILE || Would it be better to use Alamofire? -


i trying upload image, , text file(uploading data).

so far can upload image alone correctly, , upload text file data uploading .txt alone.

now need upload both image , .txt file together...

i not sure how set paramaters in ios app this....

so far how upload .txt file (basically same way upload image change "filename" , "mimetype")

func createbodywithparameters(parameters: [string : any]?, filepathkey: string?,filepathkey1: string?, imagedatakey: nsdata,imagedatakey1: nsdata, boundary: string) -> nsdata {          let body = nsmutabledata();          if parameters != nil {             (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 data)          body.appendstring("\r\n")         body.appendstring("--\(boundary)--\r\n")          return body     } 

now not sure how save both image , .txt file paramater.

this rest of swift code uploading it:

 let param = [             "id" : id,             "uuid" : uuid,             "text" : text,             "title" : title            ] [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)! nsdata     // ... body     request.httpbody = createbodywithparameters(parameters: param, filepathkey: "file",filepathkey1: "file1", imagedatakey: data nsdata,imagedatakey1: imagedata nsdata, boundary: boundary) data 

if needs see anymore of code or doesn't understand question please let me know!

thanks in advance can help!!

if don't want lost in weeds of creating complex requests, third party library alamofire smart. it's same author afnetworking, it's native swift library.

so, alamofire implementation might 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             (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 build request yourself, i'd suggest few things. first, since you're sending files of different types, might want nice type encapsulate this:

struct filepayload {     let fieldname: string     let filename: string     let mimetype: string     let payload: data } 

i'm not sure make of image/txt mime type. i'd use application/octet-stream archive.

anyway, building of request follows:

/// create request. /// /// - parameters: ///   - url:                url post sent. ///   - id:                 identifier of entry ///   - uuid:               uuid of entry ///   - text:               text. ///   - title:              title. ///   - blogattributedtext: attributed text of blog entry. ///   - image:              `uiimage` of image included. /// /// - returns: `urlrequest` 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,     // find curious see uppercase field names (i'd use lowercase consistency's sake, use whatever php 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 response not json      // use whatever field name php looking image; 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 php looking image; 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 multipart/form-data request. /// /// - parameters: ///   - parameters: optional dictionary containing keys , values passed web service. ///   - files:      list of files included in request. ///   - boundary:   `multipart/form-data` boundary /// /// - returns: `data` of body of request.  private func createbody(with parameters: [string: string]?, files: [filepayload], boundary: string) -> data {     var body = data()      if parameters != nil {         (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")         }     }      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 multipart/form-data request /// /// - returns:            boundary string consists of "boundary-" followed uuid string.  private func generateboundarystring() -> string {     return "boundary-\(nsuuid().uuidstring)" } 

where

extension data {      /// append string data     ///     /// rather littering code calls `datausingencoding` convert strings `data`, , add data `data`, wraps in nice convenient little `data` extension. converts using utf-8.     ///     /// - parameter string:       string added mutable `data`.      mutating func append(_ string: string) {         if let data = string.data(using: .utf8) {             append(data)         }     } } 

clearly swift 3 code, excised nsmutabledata reference.


Comments

Popular posts from this blog

asynchronous - C# WinSCP .NET assembly: How to upload multiple files asynchronously -

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -