上传多部分图像给出错误ios

时间:2018-06-08 04:14:18

标签: ios swift image multipartform-data

我正在尝试创建一个上传我的图片的多部分请求。但它没有按预期工作。有人可以解释我在做错的地方。

static func makeImageRequest(_ urlString: String,version:String, method:FYIHTTPMethod,formData:Data?,fileName:String, completionHandler: @escaping (_ dictionary:NSDictionary?, _ error:NSError?) -> Void ) -> URLSessionTask {
    let fullURL:String = "https://" + domain + ":8243/fyi/" + version + "/" + urlString

    let request = NSMutableURLRequest(url: URL(string: fullURL)!)
    request.timeoutInterval = 300
    request.httpMethod = method.rawValue

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

    let accessToken = FYISession.sharedInstance.getAccessToken()
    request.setValue("Bearer \(accessToken)", forHTTPHeaderField: "Authorization")
    request.setValue("application/json", forHTTPHeaderField: "Accept")
    request.setValue(fileName, forHTTPHeaderField: "image")

    let defaultConfigObject:URLSessionConfiguration = URLSessionConfiguration.default
    let defaultSession:URLSession = URLSession(configuration: defaultConfigObject, delegate: FYIURLSessionDelegate(), delegateQueue: OperationQueue.main)

    let task = defaultSession.dataTask(with: request as URLRequest, completionHandler: { data, response, error in
        guard error == nil && data != nil else {   
            DispatchQueue.main.async {
                completionHandler(nil, error as NSError?)
            }
            return
        }

        if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {           // check for http errors
            var message = ""

            if let dta = data{
                do {
                    let json = try? JSONSerialization.jsonObject(with:dta, options: JSONSerialization.ReadingOptions.allowFragments) as? NSDictionary
                    message = json??.object(forKey: "message") as? String ?? ""
                }
            }
            let httpError:NSError = NSError(domain: "HTTP", code: httpStatus.statusCode, userInfo: FYIConnection.userInfo(message))
            DispatchQueue.main.async {
                completionHandler(nil, httpError)
            }
            return
        }

        if (data != nil) {
            do {
                let json:NSDictionary = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments) as! NSDictionary
                let api_status:Bool = json.object(forKey: "api_status") as! Bool

                if (api_status){
                    DispatchQueue.main.async {
                        completionHandler(json,nil)
                    }
                }else {
                    let message:String = json.object(forKey: "message") as! String

                    let httpError:NSError = NSError(domain: FYIConnection.bundleIdentifier(), code: FYIError.apiError.rawValue, userInfo: FYIConnection.userInfo(message))
                    DispatchQueue.main.async {
                        completionHandler(nil, httpError)
                    }
                }
            } catch let jsonError as NSError {
                DispatchQueue.main.async {
                    completionHandler(nil,jsonError)
                }
            }
        }else {
            let httpError:NSError = NSError(domain: FYIConnection.bundleIdentifier(), code: 1, userInfo: FYIConnection.userInfo(""))
            DispatchQueue.main.async {
                completionHandler(nil, httpError)
            }
        }
    })
    task.resume()
    return task
}

身体是

override func createBodyWithParameters(_ parameters: [String: String]?, image: UIImage?, paths: [String]?, boundary: String) -> Data {
    let body = NSMutableData()
    let data = UIImagePNGRepresentation(image!)

    body.appendString("--\(boundary)\r\n")
    body.appendString("Content-Disposition: form-data; name=\"file\"; filename=\"" + (self.txtMobileNumber?.text ?? "") + ".png"  + "\"\r\n")
    body.appendString("\r\n")
    body.append(data!)
    body.appendString("\r\n")
     body.appendString("--\(boundary)--\r\n")
    return body as Data
}

1 个答案:

答案 0 :(得分:0)

尝试像这样修复身体:

override func createBodyWithParameters(_ parameters: [String: String]?, image: UIImage?, paths: [String]?, boundary: String) -> Data {
    let body = NSMutableData()
    let mimeType = "image/jpeg"
    let data = UIImagePNGRepresentation(image!)

    body.appendString("--\(boundary)\r\n")
    body.appendString("Content-Disposition: form-data; name=\"file\"; filename=\"" + (self.txtMobileNumber?.text ?? "") + ".png"  + "\"\r\n")
    body.appendString("Content-Type: \(mimeType)\r\n\r\n")
    body.appendString("\r\n")
    body.append(data!)
    body.appendString("\r\n")
    body.appendString("--\(boundary)--\r\n")
    return body as Data
}

也尝试添加:

request.setValue(String(describing: formData.length), forHTTPHeaderField: "Content-Length")