如何在swift中上传3个图像文件

时间:2016-12-01 09:16:42

标签: ios swift3

 func createBodyWithParameters(_ parameters: [String: String]?, filePathKey: String?, imageDataKey: Data , boundary: String) -> Data {
        let body = NSMutableData();

        if parameters != nil {
            for (key, value) in parameters! {
                body.appendString("--\(boundary)\r\n")
                body.appendString("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
                body.appendString("\(value)\r\n")
            }
        }

        let filename = "profile-image.jpg"

        let mimetype = "image/jpg"



        body.appendString("--\(boundary)\r\n")
        body.appendString("Content-Disposition: form-data; name=\"\(filePathKey!)\"; filename=\"\(filename)\"\r\n")

        body.appendString("Content-Type: \(mimetype)\r\n\r\n")
        if(imageDataKey.count != 0) {

            body.append(imageDataKey)
            //print(imageDataKey)
        }

        body.appendString("\r\n")



        body.appendString("--\(boundary)--\r\n")


        return body as Data
    }

1 个答案:

答案 0 :(得分:0)

使用以下方法..

 /**
     Call this to create a request with any HTTP method

     - parameter httpMethodType: HTTP method type post,get etc
     - parameter headers:        HTTP header key-value pair (no need to Content-Type,Accept)
     - parameter serviceName:    name of service which need to call
     - parameter paramDic:       parameters in key-value pair
     - parameter files:          array of NSData objects for file content
     - parameter success:        success callback handler
     - parameter failure:        failure callback handler
     */
    func uploadFileRequestWithParameters(_ paramDic : NSMutableDictionary?, files: NSMutableArray?, headers : NSMutableDictionary?, serviceName : NSString, success: @escaping (( _ response : HTTPURLResponse?, _ data : NSDictionary?) -> Void), failure: @escaping ((_ error : Error? ) -> Void)) {

        let urlString = BASE_URL + (serviceName as String)
        let url : URL = URL.init(string: urlString)!
        var headerDic = [String : String]()
        headerDic["Content-Type"] = "multipart/form-data"

        if headers != nil {
            let allHeaders : NSArray = headers!.allKeys as NSArray
            for key in allHeaders {
                headerDic[(key as? String)!] = (headers!.object(forKey: key)! as? String)
            }
        }
        print("Full HTTP URL -> \(urlString)")
        print("HTTP Request Method -> POST")
        print("Full HTTP Headers -> \(headerDic)")
        print("Full HTTP Parameters -> \(paramDic)")
        print("Files Array -> \(files)")

        // Begin upload

        alamoFireManager?.upload(multipartFormData: { (multipartFormData) in

            // import image to request
            for (file)  in files! {
                var mimeTypeStr = ""
                let fileDic : NSDictionary = file as! NSDictionary
                if (fileDic.object(forKey: "fileType") as? String == "image" ) {
                    mimeTypeStr = "image/png";
                }
                else if (fileDic.object(forKey: "fileType") as? String == "video" ) {
                    mimeTypeStr = "video/mp4";
                }
                else if (fileDic.object(forKey: "fileType") as? String == "gif" ) {
                    mimeTypeStr = "image/gif";
                }
                multipartFormData.append(fileDic.object(forKey: "fileData") as! Data, withName: fileDic.object(forKey: "fileKey") as! String, fileName: fileDic.object(forKey: "fileName") as! String, mimeType: mimeTypeStr)
            }

            // import parameters
            for (key, value) in paramDic! {
                multipartFormData.append((value as! String).data(using: String.Encoding.utf8)!, withName: key as! String)
            }
        },
        usingThreshold: SessionManager.multipartFormDataEncodingMemoryThreshold, to: url, method: .post, headers: headerDic as [String : String], encodingCompletion: {
                    encodingResult in

            switch encodingResult {
            case .success(let upload, _, _):
                upload.responseJSON(completionHandler: { response in
                    debugPrint(response)
                    print(response.result.value as? NSDictionary)
                })

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

像这样从你的班级调用上面的方法。

 let image : UIImage = #imageLiteral(resourceName: "splash")
        let imgData : Data = UIImagePNGRepresentation(image)!
        // let fileArray : NSArray = NSArray.init(objects: imgData)

        let parameters : NSMutableDictionary = [
            "name" : "Krishna",
        ]
        //Array to store file data
        let filesArray : NSMutableArray = []
        //fileType = image/video/gif
        //fileKey = api parameter key to receive file
        //Dictionary to hold the individual file data
        let file1 : NSMutableDictionary = [
            "fileData" : imgData,
            "fileName" : "profileImage.png",
            "fileType" : "image",
            "fileKey" : "key1"
        ]
        let file2 : NSMutableDictionary = [
            "fileData" : imgData,
            "fileName" : "image2.png",
            "fileType" : "image",
            "fileKey" : "key2"
        ]
        let file3 : NSMutableDictionary = [
            "fileData" : imgData,
            "fileName" : "image3.png",
            "fileType" : "image",
            "fileKey" : "key3"
        ]
        //Adding all file data dictionaries to array
        filesArray.add(file1)
        filesArray.add(file2)
        filesArray.add(file3)

        let header : NSMutableDictionary  = [
        "version": "1.0",
        "os": "iOS",
        "token" : HEADER_TOKEN
    ]

       uploadFileRequestWithParameters(paraDic, files: files , headers: header, serviceName: UPDATE_PROFILE_API as NSString, success: { (response, data) in
         } , failure: { (error) in

    })