如何使用Swift将多个图像上传到服务器?

时间:2016-11-03 13:55:50

标签: ios swift nsurlconnection

fun UploadRequest()
{
    if (photoArray.count > 0)
    {
        for var i=0 ; i < photoArray.count; i++
        {
            print(photoArray)
            let image = (photoArray[i] as? UIImage)!
            let imageData = UIImagePNGRepresentation(image)
            if imageData != nil{
            let request = NSMutableURLRequest(URL: NSURL(string:"MY_URL")!)
            _ = NSURLSession.sharedSession()
            request.HTTPMethod = "POST"
            let boundary = NSString(format: "---------------------------14737809831466499882746641449")
            let contentType = NSString(format: "multipart/form-data; boundary=%@",boundary)
            request.addValue(contentType as String, forHTTPHeaderField: "Content-Type")
            let body = NSMutableData()
            body.appendData(NSString(format: "\r\n--%@\r\n", boundary).dataUsingEncoding(NSUTF8StringEncoding)!)
            body.appendData(NSString(format:"Content-Disposition: form-data; name=\"profile_photo\"; filename=\"(Image_Name)\"\\r\n").dataUsingEncoding(NSUTF8StringEncoding)!)
            body.appendData(NSString(format: "Content-Type: application/octet-stream\r\n\r\n").dataUsingEncoding(NSUTF8StringEncoding)!)
            body.appendData(imageData!)
            body.appendData(NSString(format: "\r\n--%@\r\n", boundary).dataUsingEncoding(NSUTF8StringEncoding)!)

            request.HTTPBody = body

        do {
            let returnData = try NSURLConnection.sendSynchronousRequest(request, returningResponse: nil)
                    let returnString = NSString(data: returnData, encoding: NSUTF8StringEncoding)
                    print("returnString \(returnString)")
                    }
                    catch let error as NSError {
                    print(error.localizedDescription)
                                            }
            }
          task.resume()
       }
    }
}

我使用此代码但不起作用。给我文件位置空。 在这里我选择图像并存储在数组中然后我从数组上传图像。 我正在使用.php网址发送我的图片。

2 个答案:

答案 0 :(得分:0)

您可以使用Alamofire仅使用网址

将图片上传到服务器
let imageData = UIPNGRepresentation(image)!

Alamofire.upload(imageData, to: "https://httpbin.org/post").responseJSON { response in
    debugPrint(response)
} 

随意建议编辑以使其更好。

答案 1 :(得分:0)

import MobileCoreServices


func createRequest(userid: String, image: [UIImage]) throws -> NSMutableURLRequest {

   var parameters: [String : AnyObject] = [
       "userid": userid,
       "Image1": image[0],  // You need to set the UIImage Type image parameters 
       "Image2": image[1],   
       "Image3": image[2],
       "Image4": image[3]
   ]

    print(parameters)

    let boundary = generateBoundaryString()

    let url = URL(string: Your URL String)!
    let request = NSMutableURLRequest(url: url)
    request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")

    request.httpBody = try createBody(with: parameters as [String : AnyObject], boundary: boundary)

    return request
}

以下是multipart / form-data

中的上传图像和参数代码
func createBody(with parameters: [String: AnyObject], boundary: String) throws -> Data {

    var body = Data()

    for (key, value) in parameters {

        if(value is String || value is NSString) {
            body.append("--\(boundary)\r\n")
            body.append("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
            body.append("\(value)\r\n")
        }else if(value is UIImage) {
            let r = arc4random()
            let filename = "image\(r).jpg"
            let data = UIImageJPEGRepresentation(value as! UIImage,1);
            let mimetype = mimeTypeForPath(path: filename)

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

    }

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

    return body

}

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

extension String {
   var ns: NSString {
       return self as NSString
   }
   var pathExtension: String? {
       return ns.pathExtension
   }
   var lastPathComponent: String? {
       return ns.lastPathComponent
   }
}