无法将图片上传到服务器swift

时间:2016-03-23 02:00:43

标签: swift post server nsurlsession

我正在尝试将图片上传到服务器。至于现在,我得到一个错误响应,检查name ='image',错误意味着它不是。我设置它的行是:

body.appendString("Content-Disposition: form-data; name='image'; filename='test.jpg'")

我的POST请求的完整代码是这样的:我得到一个200,唯一的问题是name参数,我真的无法搞清楚。

    func imageUploadRequest()
{

    let stringUrl = "http://88.162.41.55/app_backend/public/api/v1/image?_r=1836486547600309"
    let URL = NSURL(string: stringUrl.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!)!
    let request = NSMutableURLRequest(URL: URL)
    request.HTTPMethod = "POST";
    request.setValue("Bearer \(jwtToken)", forHTTPHeaderField: "Authorization")

    let boundary = generateBoundaryString()

    request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")

    let imageData = UIImageJPEGRepresentation(image, 1)

    if(imageData == nil)  {
        print("image data is nil")
        return
    }

    let body:NSMutableData = NSMutableData()
    body.appendString("--\(boundary)\r\n")
    body.appendString("Content-Disposition: form-data; name='image'; filename='test.jpg'")
    body.appendString("Content-Type: image/jpg")
    body.appendData(imageData!)
    body.appendString("\r\n")

    body.appendString("--\(boundary)--\r\n")

    request.HTTPBody = body

    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
        data, response, error in

        if error != nil {
            print("error=\(error)")
            return
        }            
        let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
        print(" response = \(responseString!)")

        do {
            let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSDictionary
            print("json", json)
        } catch {
            print("bad things happened")
        }

    }

    task.resume()
}

有什么想法吗?非常感谢你!!

1 个答案:

答案 0 :(得分:0)

示例NSURLSession

func getMetaData(lePath:String, completion: (string: String?, error: ErrorType?) -> Void) {
// **** get_metadata ****
    let request = NSMutableURLRequest(URL: NSURL(string: "https://api.dropboxapi.com/2/files/get_metadata")!)
    let session = NSURLSession.sharedSession()
    request.HTTPMethod = "POST"

    request.addValue("Bearer ab-blah", forHTTPHeaderField: "Authorization")
    request.addValue("application/json",forHTTPHeaderField: "Content-Type")
    request.addValue("path", forHTTPHeaderField: lePath)
    let cursor:NSDictionary? = ["path":lePath]
    do {
        let jsonData = try NSJSONSerialization.dataWithJSONObject(cursor!, options: [])
        request.HTTPBody = jsonData
        print("json ",jsonData)
    } catch {
        print("snafoo alert")
    }

    let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
        if let error = error {
            completion(string: nil, error: error)
            return
        }
        let strData = NSString(data: data!, encoding: NSUTF8StringEncoding)
        //print("Body: \(strData)\n\n")
        do {
            let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options:NSJSONReadingOptions.MutableContainers);


            completion(string: "", error: nil)
        } catch {
            completion(string: nil, error: error)
        }
    })
    task.resume()

}