[英]Uploading an image from iOS/Swift to PHP server
I've looked up other solutions to this question but I don't fully understand what they're doing, and I can't get mine to work. 我已经找到了该问题的其他解决方案,但我不完全了解他们在做什么,因此我无法工作。
Here's my swift code 这是我的快速代码
let imageData = UIImageJPEGRepresentation(image, 1.0)
if(imageData == nil ) { return }
let request = NSMutableURLRequest(URL: NSURL(string: ip)!) //ip is a string variable holding my correct ip address
request.HTTPMethod = "POST"
request.setValue("Keep-Alive", forHTTPHeaderField: "Connection")
let postString = "id=\(id)&"
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: configuration, delegate: self, delegateQueue: NSOperationQueue.mainQueue())
let body = NSMutableData()
body.appendData(postString.dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData(imageData!)
request.HTTPBody = body
let task = session.uploadTaskWithRequest(request, fromData: imageData!)
task.resume()
And here's my PHP file 这是我的PHP文件
<?php
if (move_uploaded_file($_FILES['file']['tmp_name'], "image.jpg")) {
echo "File uploaded: ".$_FILES["file"]["name"];
}
else {
echo "File not uploaded";
}
?>
I have valid read and write access to the "image.jpg" file which sits on the front of my server, but it will still say that it could not upload the file. 我对服务器前部的“ image.jpg”文件具有有效的读写访问权限,但仍会说无法上传该文件。 Any thoughts? 有什么想法吗?
You're submitting the image as part of the POST request body. 您正在将图像作为POST请求正文的一部分提交。 It won't be accessible using $_FILES
. 使用$_FILES
将无法访问它。
You can Base-64 encode the image data, send the post string "id=\\(id)&image=\\(base64EncodedImageData)"
, then retrieve and decode it using $_POST
. 您可以对图像数据进行Base-64编码 ,发送发布字符串"id=\\(id)&image=\\(base64EncodedImageData)"
,然后使用$_POST
进行检索和解码。
You may want to consider using a networking library like Alamofire . 您可能要考虑使用Alamofire之类的网络库。
The manual and not recommended way: Change your PHP code to generate JSON responses. 手动(不推荐)的方式:更改PHP代码以生成JSON响应。
echo json_encode(array("success" => true,
"filename" => basename($_FILES['image']['name']));
But as was mentioned you should let Alamofire do that for you. 但是如前所述,您应该让Alamofire为您做到这一点。 You can use MSProgress for a visual progress update in Alamofire. 您可以使用MSProgress在Alamofire中进行视觉进度更新。
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 about the 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");
}
}
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.