在swift3中将图像上传到服务器

时间:2017-09-29 13:31:13

标签: json swift image-uploading

我想将图像作为参数与我的请求一起发送。我使用下面的代码来调用我的PUT请求,但我不知道如何将图像附加到身体上。

  func myImageUploadRequest()
    {
        let headers = [
            "content-type": "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW",
            "cache-control": "no-cache"
        ]
        let parameters = [
            [
                "name": "Name",
                "value": "Swift"
            ],
            [
                "name": "Key",
                "fileName": "123.png"
//UIImagePNGRepresentation(myImageView.image!)

            ]
        ]

        let boundary = "----WebKitFormBoundary7MA4YWxkTrZu0gW"

        var body = ""
        var error: NSError? = nil
        do{
        for param in parameters {
            let paramName = param["name"]!
            body += "--\(boundary)\r\n"
            body += "Content-Disposition:form-data; name=\"\(paramName)\""
            if let filename = param["fileName"] {
                let contentType = param["content-type"]!
                let fileContent = try String(contentsOfFile: filename as! String, encoding: String.Encoding.utf8)
                if (error != nil) {
                    print(error)
                }
                body += "; filename=\"\(filename)\"\r\n"
                body += "Content-Type: \(contentType)\r\n\r\n"
                body += fileContent
            } else if let paramValue = param["value"] {
                body += "\r\n\r\n\(paramValue)"
            }
        }
       // }//do


        let request = NSMutableURLRequest(url: NSURL(string: "http://——----docUpload/MediaUpload/")! as URL, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10.0)
        request.httpMethod = "PUT"
        request.allHTTPHeaderFields = headers
      //  request.httpBody = postData as Data
        let session = URLSession.shared
        let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
            if (error != nil) {
                print(error)
            } else {
                let httpResponse = response as? HTTPURLResponse
                print(httpResponse)
            }
        })

        dataTask.resume()
    }

        catch {
        } //new

}

我见过很多例子并试过但自己无法实现。请检查我的代码,并帮助我。

1 个答案:

答案 0 :(得分:0)

一种选择是在Base64中对图像进行编码,然后可以将其作为字符串包含在json中。虽然这个answer指的是javascript,但它解释了这种方法的优点和缺点。

对于语法检查此answer,它列出了您可能需要的所有可能选项,但下面的代码应该为您提供可以添加到请求正文的文件内容。

if let image = UIImage(named:"imageNameHere"), 
    let imageData = UIImagePNGRepresentation(image) {

    let fileContent = imageData.base64EncodedString(options: .lineLength64Characters)
}