在swift ios中使用AFNetworking上传图片

时间:2015-11-11 14:25:25

标签: ios iphone xcode swift afnetworking

我正在尝试使用swift中的AFNetworking将图像上传到我的服务器,我收到此错误The data couldn’t be read because it isn’t in the correct format.

  let manager = AFHTTPRequestOperationManager()
            let url = "http://path/to/server"
            let URL : NSURL = NSURL(string: url)!
            let req : NSURLRequest = NSURLRequest(URL: URL)
    let fileURL = NSURL(string: "file:///var/mobile/Media/DCIM/102APPLE/IMG_2623.PNG")
            manager.POST( url, parameters: nil,
                constructingBodyWithBlock: { (data: AFMultipartFormData!) in
                    do{
                        _ = try data.appendPartWithFileURL(fileURL!, name: "uploaded_file", fileName: "image.png", mimeType: "image/png")
                    }catch{
                    }
                },
                success: { (operation: AFHTTPRequestOperation!, responseObject: AnyObject!) in
                    print("\(responseObject)")
                },
                failure: { (operation: AFHTTPRequestOperation!, error: NSError!) in
                    print("\(error.localizedDescription)")
            })

任何帮助?!

2 个答案:

答案 0 :(得分:0)

我猜你不能使用像这样的文件的任意路径。尝试使用应用程序包中的图像文件开始,并使用类似NSBundle URLForResourceWithExtension的调用来获取文件。

如果要从用户的相机胶卷加载文件,则需要使用适当的API,而不是直接文件路径。 (“app sandbox”严格限制了对文件系统的直接访问。)

答案 1 :(得分:0)

在Swift 4中使用AFNetworking上传图片

let urlPath1 = "Path url here"

    let manager = AFHTTPRequestOperationManager()
    var Timestamp: String {
        return "\(NSDate().timeIntervalSince1970 * 1000)"
    }
    let operation =  manager.post(urlPath1 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()
}