作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
它不会工作,如何将图像从 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)
}
最佳答案
我已经根据用户的选择拍摄了照片,并为 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"]
]);
}
关于ios - 如何使用 Swift 将图像上传到 iOS 中的服务器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36280842/
我是一名优秀的程序员,十分优秀!