Swift 3上传图片到PHP失败

时间:2016-09-21 09:34:42

标签: php ios json swift

上传图片失败 我通过POST发送图像到php

enter image description here

enter image description here

class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

@IBOutlet var image: UIImageView!

override func viewDidLoad() {
    super.viewDidLoad()  
}

@IBAction func selectPicture(_ sender: AnyObject) {

    let ImagePicker = UIImagePickerController()
    ImagePicker.delegate = self
    ImagePicker.sourceType = UIImagePickerControllerSourceType.photoLibrary

    self.present(ImagePicker, animated: true, completion: nil)       
}

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {

    image.image = info[UIImagePickerControllerOriginalImage] as? UIImage
    self.dismiss(animated: true, completion: nil)
}

@IBAction func upload_request(_ sender: AnyObject) {
    UploadRequest()
}   

func UploadRequest()
{
    let url = URL(string: "http://127.0.0.1/imgJSON/img.php")

    let request = NSMutableURLRequest(url: url!)
    request.httpMethod = "POST"

    let boundary = generateBoundaryString()        

    request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")

    if (image.image == nil)
    {
        return
    }

    let image_data = UIImagePNGRepresentation(image.image!)

    if(image_data == nil)
    {
        return
    }

    let body = NSMutableData()

    let fname = "test.png"
    let mimetype = "image/png"

    body.append("--\(boundary)\r\n".data(using: String.Encoding.utf8)!)
    body.append("Content-Disposition:form-data; name=\"test\"\r\n\r\n".data(using: String.Encoding.utf8)!)
    body.append("hi\r\n".data(using: String.Encoding.utf8)!)

    body.append("--\(boundary)\r\n".data(using: String.Encoding.utf8)!)
    body.append("Content-Disposition:form-data; name=\"file\"; filename=\"\(fname)\"\r\n".data(using: String.Encoding.utf8)!)
    body.append("Content-Type: \(mimetype)\r\n\r\n".data(using: String.Encoding.utf8)!)
    body.append(image_data!)
    body.append("\r\n".data(using: String.Encoding.utf8)!)

    body.append("--\(boundary)--\r\n".data(using: String.Encoding.utf8)!)

    request.httpBody = body as Data        
    let session = URLSession.shared

    let task = URLSession.shared.dataTask(with: request as URLRequest) {            (
        data, response, error) in

        guard let _:Data = data, let _:URLResponse = response  , error == nil else {
            print("error")
            return
        }

        let dataString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)

        print(dataString)            
    }
    task.resume()       
}    

func generateBoundaryString() -> String
{
    return "Boundary-\(UUID().uuidString)"
}

在PHP中

if (move_uploaded_file($_FILES['file']['tmp_name'], "image.png")) {
echo "File uploaded: ".$_FILES["file"]["name"]; }

1 个答案:

答案 0 :(得分:0)

您的第二个屏幕截图显示了问题: 这是带有PHP警告的服务器回复,apache / php用户没有权限将上传的映像移动到targetdirectory,在这种情况下这将是根目录(/) - 因为你没有指定目录/路径存储图像的位置。请参阅PHP文档的Example 1

所以你应该创建一个上传目录(例如 mkdir / Appli ... / htdocs / uploads ,设置正确的权限(用于开发目的 chmod -R 777上传 )并在PHP中指定目标目录:

if (move_uploaded_file($_FILES['file']['tmp_name'], "/Appli.../htdocs/uploads/image.png")) { ...