AFNetworking使用参数上传图像

时间:2015-08-06 09:52:40

标签: ios swift afnetworking afnetworking-2

我使用此方法将数据发布到我的java servlet,但是getParameter(" 2")为空,但我仍然可以获取图像。

 let dics = NSMutableDictionary()
    dics.setObject(1, forKey: "2")
    dics.setObject(2, forKey: "3")
    manager.responseSerializer.acceptableContentTypes = NSSet(object: "text/plain") as Set<NSObject>

    manager.POST(urlstr, parameters: dics, constructingBodyWithBlock: {
        fromData in
        fromData.appendPartWithFormData(imgdata, name: "userImg")
    }, success: { (operation, responseObject)in
        println("bingo")
    }) { (operation, error) -> Void in
        println(error)
    }

我的问题是:

  1. 如何获取参数?

  2. 我想知道appendPartWithFormData(imgdata, name: "userImg"),我应该如何使用&#34; userImg&#34; ?

  3. 我使用request.getInputStream()来获取图像..

3 个答案:

答案 0 :(得分:0)

尝试使用Alamofire框架,我一定会解决您的问题。

您可以像这样上传多部分表单数据;

Alamofire.upload(
.POST,
URLString: "http://httpbin.org/post",
multipartFormData: { multipartFormData in
    multipartFormData.appendBodyPart(fileURL: unicornImageURL, name: "userImg")

},
encodingCompletion: { encodingResult in
    switch encodingResult {
    case .Success(let upload, _, _):
        upload.responseJSON { request, response, JSON, error in
            println(JSON)
        }
    case .Failure(let encodingError):
        println(encodingError)
    }
}

答案 1 :(得分:0)

我已经解决了这个问题! :^)

我发布到服务器的方式是正确的,但我获取参数的方式是错误的。关于iOS或AFN不是问题。

因为我将多表单数据发布到服务器,所以我不能使用request.getParameter(&#34; 2&#34;)来获取参数。

参数&#34; name&#34; appendPartWithFormData(imgdata, name: "userImg")中的数据是将数据与其他数据分开。

有关如何在Servlet中获取multipart / form-data参数,请单击此处:get multipart/form-data parameters in servlet

答案 2 :(得分:0)

在Swift 4中使用AFNetworking上传图像

func uploadUsingPOST_Image (urlPath: NSString, withParameter dictData: NSMutableDictionary, withImage image: UIImage, WithImageName imageName: NSString,successBlock success:@escaping (_ responceData:AnyObject)->Void) {

    let manager = AFHTTPRequestOperationManager()

    var Timestamp: String {
        return "\(NSDate().timeIntervalSince1970 * 1000)"
    }

    let operation =  manager.post(urlPath as String, parameters: dictData, constructingBodyWith: { (data:AFMultipartFormData!) -> Void in

        if image != nil {

            data.appendPart(withFileData: UIImagePNGRepresentation(image!)!, name: imageName as String, fileName: "\(Timestamp).png", mimeType: "image/png")


        }
    }, success: { (operation, responseObject) -> Void in

        success(responseObject as AnyObject)
    }) { (operation, error) -> Void in

        print(error, terminator: "")
    }

    operation?.start()
}