brar07

Member

Last active 10 months ago

  1. 10 months ago
    Thu May 19 14:09:21 2016
    brar07 started the conversation Upload Multiple Images.

    Can someone please help me on how to upload multiple images to server?

     var images: Int16 = 0
     var params: NSMutableDictionary = NSMutableDictionary()
     var imageDataArray = [UIImage]()
    
        func syncFile() {
        let myUrl = NSURL(string: "http://localhost/app/imageUpload.php")
    
        let request = NSMutableURLRequest(URL: myUrl!)
        request.HTTPMethod = "POST"
    
        let prefs:NSUserDefaults = NSUserDefaults.standardUserDefaults()
        let authToken = prefs.valueForKey("authToken") as! String
    
        let boundary = generateBoundaryString()
    
    
        request.addValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
        request.addValue("application/json", forHTTPHeaderField: "Accept")
    switch images {
        case 0:
            imageDataArray = []
        case 1:
            imageDataArray.append(self.imageView1.image!)
        case 2:
            imageDataArray.append(self.imageView1.image!)
            imageDataArray.append(self.imageView2.image!)
        case 3:
            imageDataArray.append(self.imageView1.image!)
            imageDataArray.append(self.imageView2.image!)
            imageDataArray.append(self.imageView3.image!)
        default:
            break
        }
    
    
        params = [
            "auth_code"   :  "\(authToken)",
            "id"          :  "\(idParam)",
            "file"        :  imageDataArray
            ]
    request.HTTPBody = createBodyWithParameters(params, filePathKey: "file", boundary: boundary)
    
    func createBodyWithParameters(parameters: NSMutableDictionary?, filePathKey: String?, 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).png"
                        let data = UIImagePNGRepresentation(image)
    
                        let mimetype = mimeTypeForPath(filename)
    
                        let fileKey = "file"
    
                        body.appendString("--\(boundary)\r\n")
                        body.appendString("Content-Disposition: form-data; name=\"\(fileKey)\"; filename=\"\(filename)\"\r\n")
                        body.appendString("Content-Type: \(mimetype)\r\n\r\n")
                        body.appendData(data!)
                        body.appendString("\r\n")
                        i = i + 1
                    }
                }
            }
        }
        body.appendString("--\(boundary)--\r\n")
    
        return body
    }
    
    func generateBoundaryString() -> String
    {
        return "Boundary-\(NSUUID().UUIDString)"
    }
    
    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!, nil)?.takeRetainedValue() {
            if let mimetype = UTTypeCopyPreferredTagWithClass(uti, kUTTagClassMIMEType)?.takeRetainedValue() {
                stringMimeType = mimetype as NSString as String
            }
        }
        return stringMimeType;
    }

    And here is my php code:

    <?php
    header('Content-type: application/json');
    $target_dir = "uploads";
    
    if(!file_exists($target_dir))
    {
     mkdir($target_dir, 0777, true);
    }
    $total = count($_FILES["file"]["name"]);
    for($i=0; $i < $total; $i++){
    
    $target_dir1 = $target_dir . "/" . basename($_FILES["file"]["name"][$i]);
    
    if (move_uploaded_file($_FILES["file"]["tmp_name"][$i], $target_dir1)) 
    {
        echo json_encode([
        "Message" => "The file ". basename( $_FILES["file"]["name"][$i]). " has been uploaded.",
        "Status" => "OK"
        ]);
    
    } else {
    
        echo json_encode([
        "Message" => "Sorry, there was an error uploading your file.",
        "Status" => "Error"
        ]);
    
    }
    
    
    }
    ?>

    But, when I print out the response data, I am getting error: {"Message":"Sorry, there was an error uploading your file.","Status":"Error"}

    However, if I remove the loop from php code and upload just 1 image with the same swift code, it successfully uploads that image.
    Any help would be really appreciated.
    Thanks!!

  2. Thu May 19 14:05:50 2016
    brar07 joined the forum.