ios - iPhone使用swift 4上传照片

标签 ios iphone swift

我尝试使用 swift 4 将照片从 iPhone 上传到服务器,但出现以下错误:

2018-03-29 09:49:14.145010+0530 UploadPhoto[966:16059] [MC] Lazy loading NSBundle MobileCoreServices.framework
2018-03-29 09:49:14.145873+0530 UploadPhoto[966:16059] [MC] Loaded MobileCoreServices.framework
2018-03-29 09:49:19.747734+0530 UploadPhoto[966:16059] [MC] System group container for systemgroup.com.apple.configurationprofiles path is /Users/nalin/Library/Developer/CoreSimulator/Devices/7846FF4C-D495-4B7B-BAA6-EF298F8EC805/data/Containers/Shared/SystemGroup/systemgroup.com.apple.configurationprofiles
2018-03-29 09:49:19.748561+0530 UploadPhoto[966:16059] [MC] Reading from private effective user settings.
2018-03-29 09:49:22.983192+0530 UploadPhoto[966:16134] [discovery] errors encountered while discovering extensions: Error Domain=PlugInKit Code=13 "query cancelled" UserInfo={NSLocalizedDescription=query cancelled}
The data couldn’t be read because it isn’t in the correct format.

我为此编写的代码如下:

import UIKit

class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    @IBOutlet var uiSelectedImage: UIImageView!
    @IBOutlet var tfImageName: UITextField!
    @IBOutlet var btSelectImage: UIButton!
    @IBOutlet var btUploadImage: UIButton!
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func selectImage(_ sender: UIButton) {
        let imagePickerController = UIImagePickerController();
        imagePickerController.delegate = self;
        imagePickerController.sourceType = UIImagePickerControllerSourceType.photoLibrary;
        self.present(imagePickerController, animated: true, completion: nil)
    }
    
    @IBAction func uploadImage(_ sender: UIButton) {
        let image = uiSelectedImage.image;
        let imageData = UIImageJPEGRepresentation(image!, 1.0);
        
        let url = URL(string: "http://192.168.43.174/LoginAndRegister/SavePictures.php");
        let session = URLSession(configuration: URLSessionConfiguration.default);
        var request = URLRequest(url: url!);
        request.httpMethod = "POST";
        
        //creating boundry constant
        let boundaryConstant = "----------------12345";
        let contentType = "multipart/form-data;boundary=" + boundaryConstant
        request.setValue(contentType, forHTTPHeaderField: "Content-Type");
        
        //making variable to send post data
        let uploadData = NSMutableData();
        
        //adding image to be uploaded in post data
        uploadData.append("\r\n--\(boundaryConstant)\r\n".data(using: String.Encoding.utf8)!);
        uploadData.append("Content-Disposition: form-data; name=\"picture\"; filename=\"file.png\"\r\n".data(using: String.Encoding.utf8)!);
        uploadData.append("Content-Type: image/png\r\n\r\n".data(using: String.Encoding.utf8)!)
        uploadData.append(imageData!);
        uploadData.append("\r\n--\(boundaryConstant)--\r\n".data(using: String.Encoding.utf8)!);
        
        request.httpBody = uploadData as Data;
        
        let task = session.dataTask(with: request)
        {
            (data:Data!, response: URLResponse!, error:Error!) in
            
            if error != nil
            {
                print(error);
                return;
            }
            
            do
            {
                let jsonResponse = try JSONSerialization.jsonObject(with: data!, options: .mutableLeaves) as! [String:Any];
                print(jsonResponse);
            }
            catch
            {
                print(error.localizedDescription);
            }
        }
        task.resume();
    }
    
    @objc func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        uiSelectedImage.image = info[UIImagePickerControllerOriginalImage] as? UIImage;
        self.dismiss(animated: true, completion: nil);
    }
    
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        dismiss(animated: true, completion: nil)
    }
}

服务器端如下:

<?php
    $name = $_POST["name"];
    $image = $_POST["image"];
    
    $decodeImage = base64_decode("$image");
    if(file_put_contents("pictures/" . $name . ".JPG", $decodeImage) === FALSE)
    {
        $result = array('success' => "false", 'result' => "Unable to upload image");
    }
    else
    {
        $result = array('success' => "true", 'result' => "Image Uploaded Successfully");
    }

    echo json_encode($result);
?>

最佳答案

请使用 alamofire 上传图片..

func CompleteShipmentAPI(){

    let imgData = UIImageJPEGRepresentation(signatureImageView.image!, 0.25)!

    let ShipID:NSNumber =  mdicShipmentDetails.value(forKey: "id") as! NSNumber

    // userDetails
    let paramerers:Parameters = ["ship_id":ShipID.stringValue]

    print(paramerers)

    MBProgressHUD.showAdded(to: self.view, animated: true)

    let headers: HTTPHeaders = [
        "x-api-key": AUTH_API_KEY
    ]
    let isImageOnProducts:NSNumber = mdicShipmentDetails.value(forKey: "isImageOnProducts") as! NSNumber
    let isDigitalSignature:NSNumber = mdicShipmentDetails.value(forKey: "isDigitalSignature") as! NSNumber

    Alamofire.upload(multipartFormData: { multipartFormData in

        if isDigitalSignature.stringValue == "1"{
            //SHOW
            multipartFormData.append(imgData, withName: "shipment_sign",fileName: "signature.jpg", mimeType: "image/jpg")
        }

        for (key, value) in paramerers {
            multipartFormData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key )
        }
    },to:BASE_URL+kPOST_COMPLETE_API, headers:headers){ (result) in
        switch result {
        case .success(let upload, _, _):

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

            upload.responseString { response in

                MBProgressHUD.hide(for: self.view, animated: true)

                if let strResponse:String  = response.result.value  {
                    print(strResponse)

                }
            }

        case .failure(let encodingError):
            print(encodingError)
            MBProgressHUD.hide(for: self.view, animated: true)
        }
    }
}

关于ios - iPhone使用swift 4上传照片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49548052/

相关文章:

swift - 对 subview 的引用应该弱吗?

ios - [UIViewController TableView :numberOfRowsInSection:]: unrecognized selector sent to instance

ios - 如何将 xib 转换为 Storyboard?

ios - 二进制拒绝 : Your app uses public APIs in an unapproved manner

iPhone 光线传感器 vs 相机测量光线强度

swift - 更改栏按钮图像

c++ - 为什么在 iOS 中结构对齐不同

ios - iPhone手机号码格式NSFormatter

iphone - 如何将 excel 工作表数据导入我的 ios 应用程序

ios - 无法通过在 Swift 3.2 中解析其显示为字符串格式来获取数组