【发布时间】:2017-06-10 12:06:29
【问题描述】:
我正在尝试在我的服务器上使用 Alamofire 和 PHP 上传图像,我在这里检查了所有不同的问题,但由于某种原因它无法正常工作。我已经用 HTML 测试了我的 PHP 文件,它成功上传了一张图片,所以它缩小到我的 swift 代码。
斯威夫特:
let URL = "http://example.com/post_pic.php"
let imageData = UIImageJPEGRepresentation(imageView.image!, 1)
Alamofire.upload(multipartFormData: { (multipartFormData) in
multipartFormData.append(imageData!, withName: "imageFile", mimeType: "image/jpeg")
}, to:URL)
{ (result) in
switch result {
case .success(let upload, _, _):
upload.uploadProgress(closure: { (Progress) in
print("Upload Progress: \(Progress.fractionCompleted)")
})
upload.responseJSON { response in
print(response.request) // original URL request
print(response.response) // URL response
print(response.data) // server data
print(response.result) // result of response serialization
// self.showSuccesAlert()
//self.removeImage("frame", fileExtension: "txt")
if let JSON = response.result.value {
print("JSON: \(JSON)")
}
}
case .failure(let encodingError):
print("Failure:")
print(encodingError)
}
}
PHP:
if(isset($_FILES['imageFile'])){
$errors= array();
$file_name = $_FILES['imageFile']['name'];
$file_size =$_FILES['imageFile']['size'];
$file_tmp =$_FILES['imageFile']['tmp_name'];
$file_type=$_FILES['imageFile']['type'];
$file_ext=strtolower(end(explode('.',$_FILES['imageFile']['name'])));
print_r($_FILES['imageFile']);
if(empty($errors)==true){
move_uploaded_file($file_tmp,"images/".$file_name);
}
else
{
echo '{"response":"file_move_error"}';
}
}
else
{
echo '{"response":"file_error"}';
}
我得到的回应是:
Optional(<NSHTTPURLResponse: 0x17022df20> { URL: http://example.com/post_pic.php } {
status code: 200, headers {
Connection = "Keep-Alive";
"Content-Length" = 25;
"Content-Type" = "application/json";
Date = "Wed, 25 Jan 2017 10:16:29 GMT";
"Keep-Alive" = "timeout=5, max=100";
Server = "Apache/2.4.7 (Ubuntu)";
"X-Powered-By" = "PHP/5.5.9-1ubuntu4.20";
} })
Optional(25 bytes)
SUCCESS
JSON: {
response = "file_error";
}
【问题讨论】: