0

我想问一下如何使用 Alamofire 5.0 和 swift 5 从 UIIMagePicker 控制器将图像上传到服务器。

这是我的代码,它并没有真正起作用

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        
        if let pickedImage = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
            
            let imageData = Data(pickedImage.pngData()!)
            
            let photo = UIImage.init(named: "photo")
            
            let parameters: [String: String] = ["Benutzername": "lina.str"] //var parameters: [String: Any] = [:]

            AF.upload(multipartFormData: { multipartFormData in

                multipartFormData.append(imageData, withName: "picture", fileName: "image", mimeType: "image/jpg")
                
                    for (key,value) in parameters {
                        multipartFormData.append((value ).data(using: .utf8)!, withName: key)
                    }

                guard let image = photo else { return }
                let jpegData = image.jpegData(compressionQuality: 1.0)
                    multipartFormData.append(Data((jpegData)!), withName: "photo")

            }, to: "https://mydomain/ajax/Upload.php")

                .responseString { response in
                    debugPrint(response)
            }
            
        }
        
       
     
        dismiss(animated: true, completion: nil)
    }

问题是文件没有上传图片。

4

1 回答 1

0

检查这个...

{
        let url = "https://mydomain/ajax/Upload.php"
        let imgData = imageDev.jpegData(compressionQuality: 0.1)!
        let parameters = ["Benutzername": "lina.str"]
        //Optional for extra parameter
        
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "MM-dd-yyyy-hh-mm-ss"
        let dateString = dateFormatter.string(from: Date())
        
        Alamofire.upload(multipartFormData: { multipartFormData in
            multipartFormData.append(imgData, withName: "picture",fileName: "uploads"+dateString+".jpg", mimeType: "image/jpg")
            for (key, value) in parameters {
                multipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
            } //Optional for extra parameters
        },
                         to:url,method:.post)
        { (result) in
            switch result {
            case .success(let upload, _, _):
                                    
                upload.uploadProgress(closure: { (progress) in
                    print("Upload Progress: \(progress.fractionCompleted)")
                })
                
                upload.responseJSON { response in
                    if let result = response.result.value as? [String : Any]
                    {
                        
                    }
                }
                
            case .failure(let encodingError):
                print(encodingError)
            }
        }
    }
于 2020-07-10T10:23:42.383 回答