使用ios10进行多部分请求

时间:2017-08-18 04:18:44

标签: ios swift ios10 nsurlsession multipart

我正在使用swift,iOS10处理多部分请求。

使用以下代码将图像保存到服务器。使用网址打开图片时只会收到404错误。

虽然我引用了网页 - https://newfivefour.com/swift-form-data-multipart-upload-URLRequest.html

,但我的代码中找不到什么问题

请帮忙。

func connectToServerWithImage(urlString: String, param: Any, image: UIImage, target: NSObject, action: Selector) {

    let url = URL(string: urlString)!
    var request = URLRequest(url: url)

    // set request configuration
    let boundary = "Boundary-\(UUID().uuidString)"
    request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
    request.httpMethod = "POST"

    // set body
    let body = NSMutableData()
    let paramDic = param as! Dictionary<String, String>

    // set param to body
    for (key, value) in paramDic {
        body.append("--\(boundary)\r\n".data(using: .utf8, allowLossyConversion: false)!)
        body.append("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n".data(using: .utf8)!)
        body.append("\(value)\r\n".data(using: .utf8)!)
    }

    // set image to body
    let filename = paramDic["\(paramDic["TYPE"]!)_MST_NO"]! + ".jpg"
    body.append("--\(boundary)\r\n".data(using: .utf8, allowLossyConversion: false)!)
    body.append("Content-Disposition: form-data; name=\"file\"; filename=\"\(filename)\"\r\n\r\n".data(using: .utf8, allowLossyConversion: false)!)
    body.append("Content-Type: image/jpg\r\n\r\n".data(using: .utf8, allowLossyConversion: false)!)
    body.append(UIImageJPEGRepresentation(image, 1)!)
    body.append("\r\n".data(using: .utf8, allowLossyConversion: false)!)
    body.append("--\(boundary)--\r\n".data(using: .utf8, allowLossyConversion: false)!)

    request.httpBody = body as Data

    // url configuration
    let urlConfig = URLSessionConfiguration.ephemeral
    urlConfig.timeoutIntervalForRequest = 5
    urlConfig.timeoutIntervalForResource = 5

    let session = URLSession(configuration: urlConfig)

    let dataTask = session.dataTask(with: request) { (data, response, error) in
        session.finishTasksAndInvalidate()
        DispatchQueue.main.async {
            if error == nil {

                if let httpUrlResponse = response as? HTTPURLResponse {
                    if httpUrlResponse.statusCode == 200 {
                        do {
                            let jsonObject: Dictionary<String, Any> = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! Dictionary<String, Any>

                            if jsonObject.isEmpty {
                                target.perform(action, with: ["RES_CODE:": "NULL"])
                            }
                        } catch let _ {}
                    }
                }
            }
        }
    }
    dataTask.resume()
}

1 个答案:

答案 0 :(得分:-1)

iOS 10中的Multipart API示例代码:

func Api_MultiPart()
{       
    var url_request  = URLRequest(url: URL(string: EmployerRegApi())!)
    url_request.httpShouldHandleCookies = false
    url_request.timeoutInterval = 60
    url_request.httpMethod = "POST"

    let boundary = "-----------Sample------------"
    let form_data = "multipart/form-data; boundary=\(boundary)"
    url_request.setValue(form_data, forHTTPHeaderField: "Content-Type")

    let body = NSMutableData()

    /*----------------- Company -----------------*/
    body.appendString("--\(boundary)\r\n")
    body.appendString("Content-Disposition: form-data; name=\"\(str_company_name_key)\r\n\r\n")
    body.appendString("\(str_company_name_val)\r\n")

    /*--------------- Address ID ---------------*/
    body.appendString("--\(boundary)\r\n")
    body.appendString("Content-Disposition: form-data; name=\"\(str_address2_key)\r\n\r\n")
    body.appendString("\(str_address_val)\r\n")

    /*--------------- State Code ---------------*/
    body.appendString("--\(boundary)\r\n")
    body.appendString("Content-Disposition: form-data; name=\"\(str_country_key)\r\n\r\n")
    body.appendString("\(str_country_val)\r\n")

    /*------------- Profile Image --------------*/
    if (str_photo_val != nil)
    {
        body.appendString("--\(boundary)\r\n")
        let mimetype = "image/jpg"
        let defFileName = generate_Image_Name_Multipart() //yourImageName.jpg
        let imageData = UIImageJPEGRepresentation(str_photo_val!, 1)

        body.appendString("Content-Disposition: form-data; name=\"\(str_photo_key)\"; filename=\"\(defFileName)\"\r\n")
        body.appendString("Content-Type: \(mimetype)\r\n\r\n")
        body.append(imageData!)
        body.appendString("\r\n")
    }
    body.appendString("--\(boundary)\r\n")

    url_request.httpBody = body as Data
    let postLength: String = "\(UInt(body.length))"
    url_request.setValue(postLength, forHTTPHeaderField: "Content-Length")

    let task = URLSession.shared.dataTask(with: url_request, completionHandler: { (data, response, error) in
        if error != nil{
            print("Error -> \(String(describing: error))")
            DispatchQueue.main.async {
                hideLoadingHUD(for_view: self.view)
            }
            return
        }
        do {
            let result = try JSONSerialization.jsonObject(with: data!, options: []) as? [String:AnyObject]
            print("Result -> \(String(describing: result))")
            DispatchQueue.main.async {
                hideLoadingHUD(for_view: self.view)
            }

        } catch {
            print("Error -> \(error)")
            DispatchQueue.main.async {
                hideLoadingHUD(for_view: self.view)
            }
        }
    })
    task.resume()
}


func generate_Image_Name_Multipart() -> String {
    let min: Int = 1
    let max: Int = 999
    let randNum: Int = (Int(arc4random_uniform(3)) % Int((max - min) + min))
    print("Random Number: \(randNum)")
    let dateformate = DateFormatter()
    dateformate.dateFormat = "ddMMyyyyHHmmss"
    let date: String = dateformate.string(from: Date())
    let img_name: String = "iOS_\(date)_\(randNum).jpg"
    return img_name
}