使用Alamofire在swift上传多个图像

时间:2017-01-06 05:53:00

标签: ios swift alamofire image-uploading

我正在使用以下代码将单个图像上传到服务器:

private static func urlRequestWithComponents(urlString:String, parameters:Dictionary<String, String>, imageData:NSData?, imageName: String) -> (URLRequestConvertible , NSData) {

    // create url request to send
    let mutableURLRequest = NSMutableURLRequest(URL: NSURL(string: urlString)!)
    mutableURLRequest.HTTPMethod = Alamofire.Method.POST.rawValue
    let boundaryConstant = "myRandomBoundary12345";
    let contentType = "multipart/form-data;boundary="+boundaryConstant
    mutableURLRequest.setValue(contentType, forHTTPHeaderField: "Content-Type")


    // create upload data to send
    let uploadData = NSMutableData()
    if(imageData != nil && imageData?.length != 0) {
        // add image
        uploadData.appendData("\r\n--\(boundaryConstant)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
        uploadData.appendData("Content-Disposition: form-data; name=\"\(imageName)\"; filename=\"\(StringHelper.sharedInstance.randomString(5)).png\"\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
        uploadData.appendData("Content-Type: image/png\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
        uploadData.appendData(imageData!)
    }
    // add parameters
    for (key, value) in parameters {
        uploadData.appendData("\r\n--\(boundaryConstant)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
        uploadData.appendData("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n\(value)".dataUsingEncoding(NSUTF8StringEncoding)!)
    }
    uploadData.appendData("\r\n--\(boundaryConstant)--\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
    print("upload",parameters)
    // return URLRequestConvertible and NSData
    return (Alamofire.ParameterEncoding.URL.encode(mutableURLRequest, parameters: nil).0, uploadData)
}

如何通过编辑此代码在单个参数中上传多个图像?

4 个答案:

答案 0 :(得分:34)

Swift 3 只需使用“[]”和图像上传参数就可以生成图像数组。

Alamofire.upload(multipartFormData: { multipartFormData in
            // import image to request
            for imageData in imagesData {
                multipartFormData.append(imageData, withName: "\(imageParamName)[]", fileName: "\(Date().timeIntervalSince1970).jpeg", mimeType: "image/jpeg")
            }
            for (key, value) in parameters {
                multipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
            }
        }, to: urlString,

            encodingCompletion: { encodingResult in
                switch encodingResult {
                case .success(let upload, _, _):
                    upload.responseJSON { response in

                    }
                case .failure(let error):
                    print(error)
                }

        })

答案 1 :(得分:4)

这个帮助我:

private func urlRequestWithComponentsForUploadMultipleImages(urlString:String, parameters:Dictionary<String, String>, imagesData:[Data], imageName: String) -> (URLRequestConvertible , Data) {

    // create url request to send
    var mutableURLRequest = URLRequest(url: NSURL(string: urlString)! as URL)

    mutableURLRequest.httpMethod = Alamofire.HTTPMethod.post.rawValue
    let boundaryConstant = "myRandomBoundary12345";
    let contentType = "multipart/form-data;boundary="+boundaryConstant
    mutableURLRequest.setValue(contentType, forHTTPHeaderField: "Content-Type")


    // create upload data to send
    var uploadData = Data()
    // add image
    for data in imagesData {
        uploadData.append("\r\n--\(boundaryConstant)\r\n".data(using: String.Encoding.utf8)!)
        uploadData.append("Content-Disposition: form-data; name=\"\(imageName)\"; filename=\"\(Date().timeIntervalSince1970).jpeg\"\r\n".data(using: String.Encoding.utf8)!)
        uploadData.append("Content-Type: image/jpeg\r\n\r\n".data(using: String.Encoding.utf8)!)
        uploadData.append(data)
    }
    // add parameters
    for (key, value) in parameters {
        uploadData.append("\r\n--\(boundaryConstant)\r\n".data(using: String.Encoding.utf8)!)
        uploadData.append("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n\(value)".data(using: String.Encoding.utf8)!)
    }
    uploadData.append("\r\n--\(boundaryConstant)--\r\n".data(using: String.Encoding.utf8)!)
    print("upload",parameters)
    return (mutableURLRequest , uploadData)
}

答案 2 :(得分:2)

看起来这个问题已经在SO上得到了回答,可能在多个地方。这是我找到的一个链接:

How to upload multiple images in multipart using Alamofire?

为方便起见,我会粘贴他们的解决方案,但他们说它适用于Swift 3.x:

Alamofire.upload(
multipartFormData: { multipartFormData in
    multipartFormData.append(unicornImageURL, withName: "unicorn")
    multipartFormData.append(rainbowImageURL, withName: "rainbow")
},
to: "https://httpbin.org/post",
encodingCompletion: { encodingResult in
    switch encodingResult {
    case .success(let upload, _, _):
        upload.responseJSON { response in
            debugPrint(response)
        }
    case .failure(let encodingError):
        print(encodingError)
    }
})

该解决方案似乎基于Alamofire文档中详述的推荐方法:https://github.com/Alamofire/Alamofire#uploading-multipartformdata

CX.UW.001: 03/08/2017
CX.UW.001.AUDIT: admin 

答案 3 :(得分:1)

这是我的解决方案,它将100%无错误。

        Alamofire.upload(multipartFormData: { (multipartFormData : MultipartFormData) in

            let count = imageToUpload.count

            for i in 0..<count{
                multipartFormData.append(imageToUpload[i], withName: "morephoto[\(i)]", fileName: "photo\(i).jpeg" , mimeType: "image/jpeg")

            }
            for (key, value) in parameterrs {

                    multipartFormData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key)
            }
            print(multipartFormData)
        }, to: url!) { (result) in

                switch result {
                case .success(let upload, _ , _):

                    upload.uploadProgress(closure: { (progress) in

                        print("uploding: \(progress.fractionCompleted)")
                    })

                    upload.responseJSON { response in

                    print(response.result.value!)
                    let resp = response.result.value! as! NSDictionary
                    if resp["status"] as! String == "success"{
                        print(response.result.value!)
                        let alert = UIAlertController(title: "Alert", message: "Image Upload Successful", preferredStyle: UIAlertControllerStyle.alert)
                        alert.addAction(UIAlertAction(title: "Okay", style: UIAlertActionStyle.default, handler: nil))
                        self.present(alert, animated: true, completion: nil)


                    }
                    else{

                    }


                }

            case .failure(let encodingError):
                print("failed")
                print(encodingError)

            }
        }

在这里,imagetoupload数组是我之前制作的图像数据数组。