Alamofire不适用于大图像

时间:2016-06-28 09:01:55

标签: ios xcode alamofire

我正在使用alamofire框架将图像/视频上传到服务器,当我尝试通过iphone 6s上传捕获的图像时,图像无法上传,但是当我尝试上传小图片时,它的工作非常好, alamofire支持的最大大小是多少,如果我们没有最大大小,我可以解决这个问题?

func uploadFile()  {

    //let image = UIImage(named: "ios9.jpg")
    let newimage : NSData = UIImageJPEGRepresentation(image.image!, 32)!

    let newRandomName = randomStringWithLength(32)
    let fname = (newRandomName as String) + ".jpg"

    let parameters = [
        "pic"           :NetData(data: newimage, mimeType: .ImageJpeg, filename: fname),
        "msg"     :self.msg,
        "customer_key" : self.CUSTOMER_KEY
    ]



    let urlRequest = self.urlRequestWithComponents("myURLhere", parameters: parameters)

    Alamofire.upload(urlRequest.0, data: urlRequest.1)
        .progress { (bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) in
            print("\(totalBytesWritten) / \(totalBytesExpectedToWrite)")
        }
        .responseJSON { response in
            debugPrint(response)
    }

}


func urlRequestWithComponents(urlString:String, parameters:NSDictionary) -> (URLRequestConvertible, NSData) {

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


    // create upload data to send
    let uploadData = NSMutableData()

    // add parameters
    for (key, value) in parameters {

        uploadData.appendData("\r\n--\(boundaryConstant)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)

        if value is NetData {
            // add image
            let postData = value as! NetData




            // append content disposition
            let filenameClause = " filename=\"\(postData.filename)\""
            let contentDispositionString = "Content-Disposition: form-data; name=\"\(key)\";\(filenameClause)\r\n"
            let contentDispositionData = contentDispositionString.dataUsingEncoding(NSUTF8StringEncoding)
            uploadData.appendData(contentDispositionData!)


            // append content type
            //uploadData.appendData("Content-Type: image/png\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!) // mark this.
            let contentTypeString = "Content-Type: \(postData.mimeType.getString())\r\n\r\n"
            let contentTypeData = contentTypeString.dataUsingEncoding(NSUTF8StringEncoding)
            uploadData.appendData(contentTypeData!)
            uploadData.appendData(postData.data)

        }else{
            uploadData.appendData("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n\(value)".dataUsingEncoding(NSUTF8StringEncoding)!)
        }
    }
    uploadData.appendData("\r\n--\(boundaryConstant)--\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)




    return (Alamofire.ParameterEncoding.URL.encode(mutableURLRequest, parameters: nil).0, uploadData)
}



func randomStringWithLength (len : Int) -> NSString {

    let letters : NSString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"

    var randomString : NSMutableString = NSMutableString(capacity: len)

    for (var i=0; i < len; i++){
        var length = UInt32 (letters.length)
        var rand = arc4random_uniform(length)
        randomString.appendFormat("%C", letters.characterAtIndex(Int(rand)))
    }

    return randomString
}

1 个答案:

答案 0 :(得分:0)

    Alamofire.upload(
        .POST,
        "your url",
        multipartFormData: { multipartFormData in


            multipartFormData.appendBodyPart(data: imageData!, name: "garment_image", fileName: "myImage.jpg", mimeType: "image/jpeg") // image



        },
        encodingCompletion: { encodingResult in
            switch encodingResult {
            case .Success(let upload, _, _):

                upload.progress { (bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) in
                    print("Uploading Avatar \(totalBytesWritten) / \(totalBytesExpectedToWrite)")

                print(upload.response)
                    dispatch_async(dispatch_get_main_queue(),{


                        /**
                         *  Update UI Thread about the progress
                         */
                    })
                }
                upload.responseJSON { (JSON) in
                    dispatch_async(dispatch_get_main_queue(),{
                        //Show Alert in UI

                    })
                }

            case .Failure( _):
                //Show Alert in UI
                print("Avatar failed");
            }
        }
    );