如何使用Swift将图像上传到iOS服务器?
它不会工作,如何将图像从iOS Swift应用程序发送到我的PHP服务器?
@IBAction func upload(sender: UIButton) { var imageData = UIImageJPEGRepresentation(img.image, 90) // println(imageData) let url = NSURL(string:"http://www.i35.club.tw/old_tree/test/uplo.php") //let cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData //var request = NSMutableURLRequest(URL: url, cachePolicy: cachePolicy, timeoutInterval: 10) var request = NSMutableURLRequest(URL: url) request.HTTPMethod = "POST" // set Content-Type in HTTP header let boundaryConstant = "----------V2ymHFg03esomerandomstuffhbqgZCaKO6jy"; let contentType = "multipart/form-data; boundary=" + boundaryConstant NSURLProtocol.setProperty(contentType, forKey: "Content-Type", inRequest: request) request.HTTPBody = imageData // set data //var dataString = "adkjlkajfdadf" //let requestBodyData = (dataString as NSString).dataUsingEncoding(NSUTF8StringEncoding) //request.HTTPBody = requestBodyData // request.addValue(contentType, forHTTPHeaderField: "Content-Type") request.addValue("multipart/form-data", forHTTPHeaderField: "Accept") // // set content length //NSURLProtocol.setProperty(requestBodyData.length, forKey: "Content-Length", inRequest: request) var response: NSURLResponse? = nil var error: NSError? = nil let reply = NSURLConnection.sendSynchronousRequest(request, returningResponse:&response, error:&error) let results = NSString(data:reply!, encoding:NSUTF8StringEncoding) println("API Response: \(results)") } //take photo func imagePickerController(picker: UIImagePickerController!, didFinishPickingImage image: UIImage!, editingInfo: NSDictionary!) { var selectedImage : UIImage = image img.image = selectedImage UIImageWriteToSavedPhotosAlbum(selectedImage, nil, nil, nil) self.dismissViewControllerAnimated(true, completion: nil) }
我已经根据用户的select拍摄了照片,并为Swift 2和iOS9编写了代码
func imageUploadRequest(imageView imageView: UIImageView, uploadUrl: NSURL, param: [String:String]?) { //let myUrl = NSURL(string: "http://192.168.1.103/upload.photo/index.php"); let request = NSMutableURLRequest(URL:uploadUrl); request.HTTPMethod = "POST" let boundary = generateBoundaryString() request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type") let imageData = UIImageJPEGRepresentation(imageView.image!, 1) if(imageData==nil) { return; } request.HTTPBody = createBodyWithParameters(param, filePathKey: "file", imageDataKey: imageData!, boundary: boundary) //myActivityIndicator.startAnimating(); let task = NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in if let data = data { // You can print out response object print("******* response = \(response)") print(data.length) // you can use data here // Print out reponse body let responseString = NSString(data: data, encoding: NSUTF8StringEncoding) print("****** response data = \(responseString!)") let json = try!NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers) as? NSDictionary print("json value \(json)") //var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers, error: &err) dispatch_async(dispatch_get_main_queue(),{ //self.myActivityIndicator.stopAnimating() //self.imageView.image = nil; }); } else if let error = error { print(error.description) } }) task.resume() } func createBodyWithParameters(parameters: [String: String]?, filePathKey: String?, imageDataKey: 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 = "user-profile.jpg" let mimetype = "image/jpg" 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.appendData(imageDataKey) body.appendString("\r\n") body.appendString("--\(boundary)--\r\n") return body } func generateBoundaryString() -> String { return "Boundary-\(NSUUID().UUIDString)" } }// extension for impage uploading extension NSMutableData { func appendString(string: String) { let data = string.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true) appendData(data!) } }
———下面的代码为PHP方面
<?php $firstName = $_POST["firstName"]; $lastName = $_POST["lastName"]; $userId = $_POST["userId"]; $target_dir = "media"; if(!file_exists($target_dir)) { mkdir($target_dir, 0777, true); } $target_dir = $target_dir . "/" . basename($_FILES["file"]["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", "userId" => $_REQUEST["userId"] ]); } else { echo json_encode([ "Message" => "Sorry, there was an error uploading your file.", "Status" => "Error", "userId" => $_REQUEST["userId"] ]); }
要用参数上传图像,请使用此代码,
// Your method to upload image with parameters to server. func uploadImageOne(){ var imageData = UIImagePNGRepresentation(imageView.image) if imageData != nil{ var request = NSMutableURLRequest(URL: NSURL(string:"Enter Your URL")!) var session = NSURLSession.sharedSession() request.HTTPMethod = "POST" var boundary = NSString(format: "---------------------------14737809831466499882746641449") var contentType = NSString(format: "multipart/form-data; boundary=%@",boundary) // println("Content Type \(contentType)") request.addValue(contentType, forHTTPHeaderField: "Content-Type") var body = NSMutableData.alloc() // Title body.appendData(NSString(format: "\r\n--%@\r\n",boundary).dataUsingEncoding(NSUTF8StringEncoding)!) body.appendData(NSString(format:"Content-Disposition: form-data; name=\"title\"\r\n\r\n").dataUsingEncoding(NSUTF8StringEncoding)!) body.appendData("Hello World".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!) // Image body.appendData(NSString(format: "\r\n--%@\r\n", boundary).dataUsingEncoding(NSUTF8StringEncoding)!) body.appendData(NSString(format:"Content-Disposition: form-data; name=\"profile_img\"; filename=\"img.jpg\"\\r\n").dataUsingEncoding(NSUTF8StringEncoding)!) body.appendData(NSString(format: "Content-Type: application/octet-stream\r\n\r\n").dataUsingEncoding(NSUTF8StringEncoding)!) body.appendData(imageData) body.appendData(NSString(format: "\r\n--%@\r\n", boundary).dataUsingEncoding(NSUTF8StringEncoding)!) request.HTTPBody = body var returnData = NSURLConnection.sendSynchronousRequest(request, returningResponse: nil, error: nil) var returnString = NSString(data: returnData!, encoding: NSUTF8StringEncoding) println("returnString \(returnString)") } }
我会build议看看: https : //github.com/sraj/Swift-SRWebClient
示例函数,为我工作:
func uploadImage(image:UIImage) { let imageData:NSData = UIImageJPEGRepresentation(image, 100) SRWebClient.POST("http://www.example.com/upload/") .data(imageData, fieldName:"photo", data: ["foo":"bar","baz":"qux"]) .send({(response:AnyObject!, status:Int) -> Void in // process success response },failure:{(error:NSError!) -> Void in // process failure response }) }
你会注意到上面的代码是Swift-SRWebClient Github页面上的一个稍微调整过的代码片段。 我用UIImageJPEGRepresentation
replace了NSData.dataWithData
,因为前者已被弃用。
此外,不要忘记拖动SRWebClient.swift
到您的项目文件夹,否则这将无法正常工作:)
试试这个
@IBAction func upload(sender: UIButton) { var imageData = UIImageJPEGRepresentation(img.image, 90) var url = NSURL(string: "http://www.i35.club.tw/old_tree/test/uplo.php") var request = NSMutableURLRequest(URL: url) request.HTTPMethod = "POST" request.HTTPBody = NSData.dataWithData(UIImagePNGRepresentation(imageData)) var response: NSURLResponse? = nil var error: NSError? = nil let reply = NSURLConnection.sendSynchronousRequest(request, returningResponse:&response, error:&error) let results = NSString(data:reply!, encoding:NSUTF8StringEncoding) println("API Response: \(results)") }
参考这个链接
这真是太好了,我一直在尝试使用REST来传递图片一段时间,并且不能将其格式化得恰到好处,并且不断出现超时错误。 使用createBodyWithParameters我能够使其工作。
这里是Swift 3版本的代码:func createBodyWithParameters(parameters:[String:String] ?, filePathKey:String ?, imageDataKey:UIImage,boundary:String) – > Data {var body = Data();
if parameters != nil { for (key, value) in parameters! { body.append("--\(boundary)\r\n".data(using: String.Encoding.utf8)!) body.append("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n".data(using: String.Encoding.utf8)!) body.append("\(value)\r\n".data(using: String.Encoding.utf8)!) } } let filename = "user-profile.jpg" let mimetype = "image/jpg" body.append("--\(boundary)\r\n".data(using: String.Encoding.utf8)!) body.append("Content-Disposition: form-data; name=\"\(filePathKey!)\"; filename=\"\(filename)\"\r\n".data(using: String.Encoding.utf8)!) body.append("Content-Type: \(mimetype)\r\n\r\n".data(using: String.Encoding.utf8)!) body.append(UIImageJPEGRepresentation(imageDataKey, 1)!) //body.appendData(imageDataKey) body.append("\r\n".data(using: String.Encoding.utf8)!) body.append("--\(boundary)--\r\n".data(using: String.Encoding.utf8)!) return body }