【问题标题】:Swift 3 upload image to PHP-ServerSwift 3 上传图片到 PHP-Server
【发布时间】:2018-03-03 18:55:51
【问题描述】:

我正在尝试从 iOS 照片库或相机上传一张简单的图片 使用 PHP 5.4 到我的服务器 移动上传的文件失败,假设 $_FILES 不包含数据

func uploadImage() {
    let image = self.imageView.image!
    //let image = UIImage.init(named: "myImage")

    let imgData = UIImageJPEGRepresentation(image, 1)!

    print(imgData)

    let parameters = ["name": "Frank Bergmann"]

    Alamofire.upload(multipartFormData: { multipartFormData in
        multipartFormData.append(imgData, withName: "userfile",fileName: "file.jpg", mimeType: "image/jpg")
        for (key, value) in parameters {
            multipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
        }
    },
                     to:"https://myserver.de/apple_imageupload.php")
    { (result) in
        switch result {
        case .success(let upload, _, _):

            upload.uploadProgress(closure: { (progress) in
                print("Upload Progress: \(progress.fractionCompleted)")
            })

            upload.responseJSON { response in
                print(response.result.value!)  
            }

        case .failure(let encodingError):
            print(encodingError)  
        }
    }
}

带有 Alamofire 的 SWIFT 3

服务器上的 PHP 代码

<?php
//$files = print_r($_FILES, 1);
//echo json_encode($files);

$uploaddir = "../bookcase/";

$file = basename($_FILES['userfile']['name']);

$uploadfile = $uploaddir . $file;

if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
    $data=Array("Reply"=>"Image $file saved at server (bookcase)");
} else {
    $data=Array("Reply"=>"Image not saved - Name:".$_FILES['userfile']['name']);
}

echo json_encode($data);

xcode 中的输出

Select Button pressed
Upload Button pressed
208743 bytes
{"Reply":"Image not saved - Name:"}

假设上传后 $_FILES 不存在 - 任何人都可以帮助我

【问题讨论】:

标签: php swift image upload


【解决方案1】:

将 imgData 声明中的“1”更改为 0.1

let imgData = UIImageJPEGRepresentation(image, 0.1)!

这会改变上传图片的质量。其中 1 是最高质量,0 是最低质量(压缩程度最高)。当我使用“1”时我遇到了同样的问题,但是当我设置为较低的质量时对我有用。图像质量对我来说明显不好,所以这个解决方案也可能对你有用。您还可以尝试其他质量/压缩量,例如 0.2 或 0.5 或更高。这也可能对你有用,你只需要测试它。

我推测这是因为图像太大(未压缩时),服务器无法处理。

【讨论】:

  • 谢谢 :) 我会尝试,也许它会工作。同时,我通过 webview 和 php 上传解决了这个问题。
猜你喜欢
  • 1970-01-01
  • 2017-06-10
  • 1970-01-01
  • 2011-03-16
  • 2017-05-29
  • 2017-10-25
  • 2017-03-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多