swift - Upload image with alamofire -


i'm trying upload image server alamofire code doesn't work. code:

var parameters = ["image": "1.jpg"]     let image = uiimage(named: "1.jpg")     let imagedata = uiimagepngrepresentation(image)     let urlrequest = urlrequestwithcomponents("http://tranthanhphongcntt.esy.es/task_manager/iosfileupload/", parameters: parameters, imagedata: imagedata)     alamofire.upload(urlrequest.0, data: urlrequest.1)         .progress { (byteswritten, totalbyteswritten, totalbytesexpectedtowrite) in             println("\(totalbyteswritten) / \(totalbytesexpectedtowrite)")         }         .responsejson { (request, response, json, error) in             println("request \(request)")             println("response \(response)")             println("json \(json)")             println("error \(error)")     } 

and urlrequestwithcomponents methos:

func urlrequestwithcomponents(urlstring:string, parameters:dictionary<string, string>, imagedata:nsdata) -> (urlrequestconvertible, nsdata) {      // create url request send     var mutableurlrequest = nsmutableurlrequest(url: nsurl(string: urlstring)!)     mutableurlrequest.httpmethod = alamofire.method.post.rawvalue     let boundaryconstant = "myrandomboundary12345";     let contenttype = "multipart/form-data;boundary="+boundaryconstant     mutableurlrequest.setvalue(contenttype, forhttpheaderfield: "content-type")        // create upload data send     let uploaddata = nsmutabledata()      // add image     uploaddata.appenddata("\r\n--\(boundaryconstant)\r\n".datausingencoding(nsutf8stringencoding)!)     uploaddata.appenddata("content-disposition: form-data; name=\"file\"; filename=\"file.png\"\r\n".datausingencoding(nsutf8stringencoding)!)     uploaddata.appenddata("content-type: image/png\r\n\r\n".datausingencoding(nsutf8stringencoding)!)     uploaddata.appenddata(imagedata)      // add parameters     (key, value) in parameters {         uploaddata.appenddata("\r\n--\(boundaryconstant)\r\n".datausingencoding(nsutf8stringencoding)!)         uploaddata.appenddata("content-disposition: form-data; name=\"\(key)\"\r\n\r\n\(value)".datausingencoding(nsutf8stringencoding)!)     }     uploaddata.appenddata("\r\n--\(boundaryconstant)--\r\n".datausingencoding(nsutf8stringencoding)!)        // return urlrequestconvertible , nsdata     return (alamofire.parameterencoding.url.encode(mutableurlrequest, parameters: nil).0, uploaddata) } 

and in console:

request { url: http://tranthanhphongcntt.esy.es/task_manager/iosfileupload/ } response optional( { url: http://tranthanhphongcntt.esy.es/task_manager/iosfileupload/ } { status code: 200, headers { "accept-ranges" = bytes; connection = close; "content-length" = 345; "content-type" = "text/html"; date = "tue, 25 aug 2015 10:52:01 gmt"; "last-modified" = "mon, 24 aug 2015 03:54:55 gmt"; server = apache; } }) json nil error optional(error domain=nscocoaerrordomain code=3840 "the operation couldn’t completed. (cocoa error 3840.)" (invalid value around character 0.) userinfo=0x7f8c68c1c130 {nsdebugdescription=invalid value around character 0.})

my php content:

<? php  echo $_files['image']['name'].  '<br/>';      //ini_set('upload_max_filesize', '10m');  //ini_set('post_max_size', '10m');  //ini_set('max_input_time', 300);  //ini_set('max_execution_time', 300);      $target_path = "uploads/";    $target_path = $target_path.basename($_files['image']['name']);    try {    //throw exception if can't move file    if (!move_uploaded_file($_files['image']['tmp_name'], $target_path)) {      throw new exception('could not move file');    }      echo "the file ".basename($_files['image']['name']).    " has been uploaded";  } catch (exception $e) {    die('file did not upload: '.$e - > getmessage());  } ?>

my code followed suggestion: uploading file parameters using alamofire .please me, thanks

while rob's answer correct, here's swift 2.0 version, upload progress update.

just copy , paste following code, change upload url, , add in parameters. should work charm.

ps: mrprogress awesome library progress update!

    let apitoken = "abcde"     alamofire.upload(         .post,         "http://sample.com/api/upload",         multipartformdata: { multipartformdata in             multipartformdata.appendbodypart(data: imagedata, name: "yourparamname", filename: "imagefilename.jpg", mimetype: "image/jpeg")             multipartformdata.appendbodypart(data: apitoken.datausingencoding(nsutf8stringencoding, allowlossyconversion: false)!, name :"api_token")             multipartformdata.appendbodypart(data: otherbodyparamvalue.datausingencoding(nsutf8stringencoding, allowlossyconversion: false)!, name :"otherbodyparamname")         },         encodingcompletion: { encodingresult in             switch encodingresult {             case .success(let upload, _, _):                 upload.progress { (byteswritten, totalbyteswritten, totalbytesexpectedtowrite) in                     print("uploading avatar \(totalbyteswritten) / \(totalbytesexpectedtowrite)")                     dispatch_async(dispatch_get_main_queue(),{                         /**                         *  update ui thread progress                         */                     })                 }                 upload.responsejson { (json) in                     dispatch_async(dispatch_get_main_queue(),{                         //show alert in ui                         print("avatar uploaded");                     })                 }              case .failure(let encodingerror):                 //show alert in ui                 print("avatar uploaded");             }         }     ); 

Comments

Popular posts from this blog

java - UnknownEntityTypeException: Unable to locate persister (Hibernate 5.0) -

python - ValueError: empty vocabulary; perhaps the documents only contain stop words -

ubuntu - collect2: fatal error: ld terminated with signal 9 [Killed] -