当前位置: 首页 > 知识库问答 >
问题:

图片上传在swft 4使用alamofire 4与PHP不工作在更新版本

莫誉
2023-03-14

我做了我的项目与图像上传到服务器使用PHP脚本。它在Swift 2和alamofire上运行良好。

用alamofire 4更新到Swift 4后,上传代码不起作用。

@IBAction func create(_ sender: AnyObject) {

    showLoadingMode (loading: self)

    let name = grpnametf.text
    let defaults = UserDefaults.standard

    let member_id = defaults.object(forKey: "id") as! String
    let country = defaults.object(forKey: "country") as! String


    if (name != "" ){

        self.reachability = Reachability.init()
        if((self.reachability?.connection) != .none)
        {
       // let reachability = Reachability2.reachabilityForInternetConnection()

        //if reachability.isReachable() || reachability.isReachableViaWiFi() || reachability.isReachableViaWWAN(){

        //if (network.reachability.whenReachable != nil) {
            let image : NSData = UIImageJPEGRepresentation(profileimg.image!, 32)! as NSData


          //let picname = "1"
            let grpiconname : String = member_id + name!

            let formattedstring = grpiconname.replacingOccurrences(of: " ", with: "_")

            let parameters = [
                "id" : member_id,
                "g_name" : name!,
                "type" : "ios",
                "country" : country,
                "fileName" : formattedstring+".jpg"

                ]
            let url = "http://www.kidsedin.com/nriconnect/webpage/index.php/App/creategroup"

            Alamofire.request(url, method: .get, parameters: parameters, encoding: URLEncoding.default).responseJSON { response in

                if let j = response.result.value {


                    actInd.stopAnimating()

                    //swifty json

                    // print(j)
                    let result = (j as AnyObject).stringValue
                   // print (result)

                    if result != "0" {

                       // let urlRequest = self.urlRequestWithComponents(urlString: "http://www.kidsedin.com/nriconnect/webpage/index.php/app/pic_upload?grpicon_name="+formattedstring+"&groupid="+result!, parameters: parameters as NSDictionary)

                        //print(urlRequest)

                       // let imageToUploadURL = Bundle.main.url(forResource: "bg", withExtension: "jpg")

                        //let url = "http://www.kidsedin.com/nriconnect/webpage/index.php/app/testpicupload"

                            // Use Alamofire to upload the image

                        print(UIImageJPEGRepresentation(self.profileimg.image!, 1))
                        Alamofire.upload(multipartFormData: { (multipartFormData) in
                            multipartFormData.append(UIImageJPEGRepresentation(self.profileimg.image!, 0.2)!, withName: "photo_path", fileName: formattedstring+".jpg", mimeType: "image/jpeg")
                            for (key, value) in parameters {
                                multipartFormData.append(value.data(using: .utf8)!, withName: key)
                            }
                        }, to:"http://www.kidsedin.com/nriconnect/webpage/index.php/app/testpicupload?grpicon_name="+formattedstring+"&groupid="+result!+"&type=ios")
                        { (result) in
                            switch result {
                            case .success(let upload, , ):

                                upload.uploadProgress(closure: { (progress) in
                                   // print (progress)
                                })

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

                            case .failure(let encodingError): break
                                //print(encodingError.localizedDescription)
                            }
                        }
                    }

                    else if result == "0"{

                        let alert = UIAlertController(title: "", message: "Group name already exist", preferredStyle: .alert)
                        let okAction = UIAlertAction(title: "Ok", style: .default, handler:nil)
                        alert.addAction(okAction)

                        self.present(alert, animated: true, completion: nil)


                        actInd.stopAnimating()

                    }else
                    {
                        let alert = UIAlertController(title: "", message: "Group creation failed. Something went wrong", preferredStyle: .alert)
                        let okAction = UIAlertAction(title: "Ok", style: .default, handler: nil)

                        alert.addAction(okAction)

                        self.present(alert, animated: true, completion: nil)

                        actInd.stopAnimating()
                    }
                }

            }
        }

        else
        {
            //print("Internet connection FAILED")
            let alert = UIAlertController(title: "No internet connection. Please check it", message: "Make sure your device is connected to the internet.", preferredStyle: .alert)
            let okAction = UIAlertAction(title: "Ok", style: .default, handler: nil)

            alert.addAction(okAction)

            self.present(alert, animated: true, completion: nil)


            actInd.stopAnimating()
        }
    }

    else{

        if( name == "" ){

            let alert = UIAlertController(title: "", message: "Name field is empty", preferredStyle: .alert)
            let okAction = UIAlertAction(title: "Ok", style: .default, handler: nil)

            alert.addAction(okAction)

            self.present(alert, animated: true, completion: nil)

            actInd.stopAnimating()
        }

    }
}

以上是我更新的代码。请建议我应该怎么做来解决这个错误。或提供我改变这个图像上传使用PHP脚本的解决方案。

共有1个答案

公良云
2023-03-14

这也许对你有帮助

import Foundation
import Alamofire

class UploadImageController: NSObject {

// MARK: - shared

static let shared  = UploadImageController()

// MARK: - init

let decoder = JSONDecoder()

// MARK: - uploadImageOnly

func uploadImageWith(endUrl: String, photo: UIImage?, parameters: [String : Any]?, headers: HTTPHeaders?, completion: @escaping (_ success: Bool, _ uploadImageResponse: UploadImageResponse?) -> Void ) {

    Alamofire.upload(multipartFormData: { (multipartFormData) in

        if let data = UIImageJPEGRepresentation(photo!, 0.5) {

            multipartFormData.append(data, withName: "invoice", fileName: "invoice.jpeg", mimeType: "invoice/jpeg")
        }

    }, usingThreshold: SessionManager.multipartFormDataEncodingMemoryThreshold, to: endUrl, method: .post, headers: headers) { (result) in

        switch result {

        case .failure(let error):
            print("UploadImageController.requestWith.Alamofire.usingThreshold:", error)
            completion(false, nil)

        case .success(request: let upload, streamingFromDisk: _, streamFileURL: _):

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

            upload.responseJSON(completionHandler: { (response) in

                switch response.result {

                case .failure(let error):

                    print("UploadImageController.requestWith.Alamofire.upload.responseJSON:", error)

                    completion(false, nil)

                case .success( _):

                    print("UploadImageController.requestWith.Alamofire.upload.responseJSON Succes")
                    guard let data = response.data else { return }

                    do {

                        let uploadImageResponse = try self.decoder.decode(UploadImageResponse.self, from: data)

                        completion(true, uploadImageResponse)

                    } catch let jsonError {

                        print("Error serializing json.ProfileController.getProfile:", jsonError)
                        completion(false, nil)
                    }
                }
            })
        }
    }
}

// MARK: - uploadImageWithParameters

func uploadImageWithParametersAnd(endUrl: String, photo: UIImage?, parameters: [String : Any]?, headers: HTTPHeaders?, completion: @escaping (_ success: Bool, _ addInvoiceResponse: AddInvoiceResponse?) -> Void ) {

    Alamofire.upload(multipartFormData: { (multipartFormData) in

        if let data = UIImageJPEGRepresentation(photo!, 0.5) {

            multipartFormData.append(data, withName: "invoicePicture", fileName: "invoicePicture.jpeg", mimeType: "invoice/jpeg")
        }

        for (key, value) in parameters! {
            multipartFormData.append("\(value)".data(using: String.Encoding.utf8)!, withName: "\(key)")
        }


    }, usingThreshold: SessionManager.multipartFormDataEncodingMemoryThreshold, to: endUrl, method: .post, headers: headers) { (result) in

        switch result {

        case .failure(let error):
            print("UploadImageController.requestWith.Alamofire.usingThreshold:", error)
            completion(false, nil)

        case .success(request: let upload, streamingFromDisk: _, streamFileURL: _):

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

            upload.responseJSON(completionHandler: { (response) in

                switch response.result {

                case .failure(let error):

                    print("UploadImageController.requestWith.Alamofire.upload.responseJSON:", error)

                    completion(false, nil)

                case .success( _):

                    print("UploadImageController.requestWith.Alamofire.upload.responseJSON Succes")
                    guard let data = response.data else { return }

                    do {

                        let addInvoiceResponse = try self.decoder.decode(AddInvoiceResponse.self, from: data)

                        completion(true, addInvoiceResponse)

                    } catch let jsonError {

                        print("Error serializing json.ProfileController.getProfile:", jsonError)
                        completion(false, nil)
                    }
                }
            })
        }
    }
 }
}
 类似资料:
  • 本文向大家介绍ajax图片上传,图片异步上传,更新实例,包括了ajax图片上传,图片异步上传,更新实例的使用技巧和注意事项,需要的朋友参考一下 最近在研究ajax图片上传,图片异步上传,更新,留作参考。 直接上源码吧: js源码: js:  html代码: 服务器端使用一般处理程序: 程序使用的是framework4.0,所以使用了一些扩展方法。 JsonTesult类代码: StatusMess

  • 我有mp3上传表。当我在服务器上上传我的项目时,mp3上传不起作用,我回显文件名、大小和tmp_名称,它返回的文件大小为0,tmp_名称为空。但当上传jpg图像时,我得到了文件名、大小、tmp_名称。 我在下面的代码中提到的内容:上传表单: Ajax调用代码: 和我的服务器端代码: 这里是参考链接文件上传

  • 问题内容: 我正在写一个Ajax联系表格。我也写了我自己的验证码。但是我有刷新图像的问题。我这样写: 重新加载验证码: 和captcha_p.php文件: 并且我已将以下行添加到capcha.php中: 它在Google Chrome和Safari上完美运行。但不适用于Firefox和资源管理器。 谢谢! 问题答案: 看来Firefox和IE正在缓存图像。为防止这种情况,请将时间戳记附加到URL和

  • 我在Node.js应用程序中使用multer和cloudinary上传图像。当我处于开发模式时,它工作得非常好,但在部署到heroku后,我在浏览器控制台中得到错误,因为服务器响应的状态是503(服务不可用)。当我检查heroku日志时,它显示为at=error code=h12desc=“request timeout”method=post path=“/api/users/upload/av

  • 我对mac相当陌生,并尝试通过玩来学习一些东西。目前,我正在尝试在我的macbook上运行XAMPP上的新PHP版本。我为此阅读了不同的线程和教程(例如,有没有办法在XAMPP中使用两个PHP版本?)但我被卡住了。这是我得到的: macOS Mojave with XAMPP 5.6.31-0 with PHP version 5.6.31 PHP

  • 我正在用一些初始数据绘制一个条形图,然后在单击按钮时尝试更新。我收到错误“未捕获的类型错误:无法读取未定义的属性'长度'”。单击更新后,将发生错误。如何解决此问题并启用更新功能以绘制新的条形图? D3代码: