将多个映像从Swift上传到PHP

时间:2017-07-11 14:07:54

标签: ios swift

以前似乎已经问过这个问题,但没有答案对我很有帮助。我有一个应用程序,我创建了自己的ImagePicker,从用户的相机胶卷中选择多个图像。我现在需要将这些图像上传到PHP脚本。当我只需要上传一张图片时,一切正常。问题是,我不知道如何更改我的代码以上传多个图像。

开始发布的代码(仅限与上传相关的最重要代码)

let param = ["request":"uploadImagesAndParams", "someParam": self.txtSomeTextField.text!]

        let boundary = generateBoundaryString()

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

        //Here I am just selecting the first image in my UIImage array (selectedImages). I need to be able to select all of them and upload it.
        let imageData = UIImageJPEGRepresentation((selectedImages?[0])!, 1)

        if(imageData == nil)  { return; }

        request.httpBody = createBodyWithParameters(parameters: param,
                                                    filePathKey: "image",
                                                    imageDataKey: imageData! as NSData,
                                                    boundary: boundary) as Data

要上传的代码

//Upload Function
    func createBodyWithParameters(parameters: [String: String]?, filePathKey: String?, imageDataKey: NSData, boundary: String) -> NSData {
        let body = NSMutableData();

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

        let filename = "user-profile.jpg"
        let mimetype = "image/jpg"

        body.appendString(string: "--\(boundary)\r\n")
        body.appendString(string: "Content-Disposition: form-data; name=\"\(filePathKey!)\"; filename=\"\(filename)\"\r\n")
        body.appendString(string: "Content-Type: \(mimetype)\r\n\r\n")
        body.append(imageDataKey as Data)
        body.appendString(string: "\r\n")



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

        return body
    }



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

2 个答案:

答案 0 :(得分:0)

以下是使用Alamofire

上传多张图片的代码段

假设您有要上传到服务的图像数组

for aIndex in 0..<imgArray.count{
   if let imageData = UIImageJPEGRepresentation(imgArray[aIndex], 0.5) {
        multipartFormData.append(imageData, withName: "Image\(aIndex).jpg")
        }
   }

希望这会对你有所帮助

答案 1 :(得分:0)

我想出了没有操作的方法。下面的方法将多个图像上传到PHP服务器。希望这有助于其他人。

导入以下

import MobileCoreServices

添加以下

var selectedImages: [UIImage]?
var params: NSMutableDictionary = NSMutableDictionary()

发出请求的函数

    function upload() {
            // Retrieve server URL
            let serverUrl = dbConn.OnlineDBConnectionString()

            // Define server side script URL
            let scriptUrl = serverUrl + "evalue8_api.php"

            let myUrl = NSURL(string: scriptUrl);

            let request = NSMutableURLRequest(url:myUrl! as URL);
            request.httpMethod = "POST";

            //Note the [] after image
             params = ["someVariable": self.txtMytextfield.text!, "image[]": selectedImages!]

            let boundary = generateBoundaryString()

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

            request.httpBody = createBodyWithParameters(parameters: params, boundary: boundary) as Data

            _ = URLSession.shared.dataTask(with: request as URLRequest) {
                data, response, error in

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

                do {
                    let parsedData = try JSONSerialization.jsonObject(with: data!, options: []) as! NSDictionary

                    //print(parsedData)
                    let success = parsedData["response"] as! Bool

                    DispatchQueue.main.async {
                        if (success) {
                            //Do something
                        }
                    }
                } catch {
                    print(error.localizedDescription)
                }
            }.resume()
        }

其他所需功能

//Upload Function
    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(string: "--\(boundary)\r\n")
                    body.appendString(string: "Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
                    body.appendString(string: "\(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(path: filename)

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

    func mimeTypeForPath(path: String) -> String {
        let pathUrl = NSURL(string: path)

        let pathExtension = pathUrl!.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;
    }

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

需要延期

    extension NSMutableData {

    func appendString(string: String) {
        let data = string.data(using: String.Encoding.utf8, allowLossyConversion: true)
        append(data!)
    }
}