ios – 在Swift中使用其他参数上传多个图像

前端之家收集整理的这篇文章主要介绍了ios – 在Swift中使用其他参数上传多个图像前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
现在,我一直只通过下面给出的代码将一个图像上传到服务器端脚本的服务器上.现在我有一个UI Image数组,我想知道如何使用UIImageJPEGRepresentation(myImageView.image!,0.1)将所有图像发布到UIImageView数组中?
func uploadImage()
{
    let postPictureUrl = NSURL(string: "http://www.23look.com/merchant/verify")
    let request = NSMutableURLRequest(URL: postPictureUrl!)
    request.HTTPMethod="POST"

    let param=[
        "mer_name" : shopNameUITF.text!,"mer_tel" : shopTelephoneUITF.text!,"mer_address" : shopAddressUITF.text!,"lat" : "39.6892","lng" : "115.9239","token": KeychainWrapper.stringForKey("tokenValue")!,"mer_type": "smalll"
    ]

    let abc =  KeychainWrapper.stringForKey("tokenValue")!

    let boundary = generateBoundaryString()

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

    let imageData = UIImageJPEGRepresentation(myImageView.image!,0.1)

    if imageData==nil { print("image data is nil"); return }

    request.HTTPBody = createBodyWithParameters(param,filePathKey: "mer_license",imageDataKey: imageData!,boundary: boundary)

    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
        data,response,error in

        if error != nil {
            print("error=\(error)")
            return
        }

        //You can print out response object
        print("***** response = \(response)")

        // Print out reponse body
        let responseString = NSString(data: data!,encoding: NSUTF8StringEncoding)
        print("**** response data = \(responseString!)")

        do {

            let json = try NSJSONSerialization.JSONObjectWithData(data!,options: .MutableContainers) as? NSDictionary

            dispatch_async(dispatch_get_main_queue(),{
                print(NSString(data: data!,encoding:NSUTF8StringEncoding)!)
                print(json)
            })

        } catch let err {
            print(err)
        }
    }
    task.resume()
}

func generateBoundaryString() -> String {
    return "Boundary-\(NSUUID().UUIDString)"
}

func createBodyWithParameters(parameters:[String:String]?,filePathKey: String?,imageDataKey:NSData,boundary: String) -> NSData {

    var 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 = "user-profile.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")
    body.appendData(imageDataKey)
    body.appendString("\r\n")

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

    return body
}

它需要以下参数:

mer_name – 字符串

mer_tel – 字符串

mer_address – 字符串

lng – 字符串

lat – string

mer_licence – 文件类型(这是我的图片上传的地方)

token – 字符串

mer_type – 字符串

解决方法

您应该在createBodyWithParameters中进行更改,如下所示………

当你有多个图像时……

func createBodyWithParameters(parameters: NSMutableDictionary?,boundary: String) -> NSData {
    let body = NSMutableData()

    if parameters != nil {
        for (key,value) in parameters! {

            if(value is String || value is NSString){
                body.appendString("--\(boundary)\r\n")
                body.appendString("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
                body.appendString("\(value)\r\n")
            }
            else if(value is [UIImage]){
                var i = 0;
                for image in value as! [UIImage]{
                    let filename = "image\(i).jpg"
                    let data = UIImageJPEGRepresentation(image,1);
                    let mimetype = mimeTypeForPath(filename)

                    body.appendString("--\(boundary)\r\n")
                    body.appendString("Content-Disposition: form-data; name=\"\(key)\"; filename=\"\(filename)\"\r\n")
                    body.appendString("Content-Type: \(mimetype)\r\n\r\n")
                    body.appendData(data!)
                    body.appendString("\r\n")
                    i++;
                }


            }
        }
    }
    body.appendString("--\(boundary)--\r\n")
    //        NSLog("data %@",NSString(data: body,encoding: NSUTF8StringEncoding)!);
    return body
}

func generateBoundaryString() -> String {
    return "Boundary-\(NSUUID().UUIDString)"

}

func mimeTypeForPath(path: String) -> String {
    let pathExtension = path.pathExtension
    var stringMimeType = "application/octet-stream";
    if let uti = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension,pathExtension!,nil)?.takeRetainedValue() {
        if let mimetype = UTTypeCopyPreferredTagWithClass(uti,kUTTagClassMIMEType)?.takeRetainedValue() {
            stringMimeType = mimetype as NSString as String
        }
    }
    return stringMimeType;
}



func createRequest (param : NSMutableDictionary,strURL : String) -> NSURLRequest {

    let boundary = generateBoundaryString()

    let url = NSURL(string: strURL)
    let request = NSMutableURLRequest(URL: url!)

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

    return request
}

猜你在找的iOS相关文章