图像上传到laravel服务器iOS

时间:2017-01-17 13:44:49

标签: ios laravel

在我的应用中,我想将几​​张图片上传到服务器。问题是我无法上传它。相同的代码适用于服务器,我可以上传图像。但是对于laravel服务器,我无法上传它。

代码

    func sendImageWithParams(image:UIImage, url : String,photoParamKey:String,params : [String:String],quality:CGFloat=0.7,getResponse : Response) -> Void {

        let request = NSMutableURLRequest(URL: NSURL(string: url)!);
        request.HTTPMethod = "POST"
        let boundary = generateBoundaryString()
        request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
        let imageData = UIImageJPEGRepresentation(image, quality)

        if(imageData==nil)  { return; }

        request.HTTPBody = createBodyWithParameters(params,photoParamKey:photoParamKey, imageDataKey: imageData!, boundary: boundary)
        request.timeoutInterval = 20.0

        let task =  NSURLSession.sharedSession().dataTaskWithRequest(request,
                                                                     completionHandler: {
                                                                        (data, response, error) -> Void in
                                                                        if let data = data {

                                                                            getResponse(success: data, error: nil)


                                                                        } else if let error = error {
                                                                            getResponse(success: nil , error: error)
                                                                        }
        })
        task.resume()

    }

    func generateBoundaryString() -> String {
        return "Boundary-\(NSUUID().UUIDString)"
    }
    func createBodyWithParameters(parameters: [String: String]?,photoParamKey : String,imageDataKey: NSData, boundary: String) -> NSData {

        let body = NSMutableData();

        if parameters != nil {
            for (key, value) in parameters! {
                body.appendString("--\(boundary)\r\n")
                body.appendString("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
                body.appendString("\(value)\r\n")
            }
        }

        let mimetype = "image/jpg"
        let filename    = "image"
        body.appendString("--\(boundary)\r\n")
        body.appendString("Content-Disposition: form-data; name=\"\(photoParamKey)\"; filename=\"\(filename)\"\r\n")
        body.appendString("Content-Type: \(mimetype)\r\n\r\n")
        body.appendData(imageDataKey)
        body.appendString("\r\n")

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


        return body
    }

}

我得到的回应

<OS_dispatch_data: data[0x7fe220759040] = { leaf, size = 30, buf = 0x7fe22063cff0 }>

Optional({"status_code":422,"status":"Failure","response":{"userId":["The user id field is required."],"propertyId":["The property id field is required."],"title":["The title field is required."],"description":["The description field is required."]},"message":"422 Unprocessable Entity","debug":{"line":22,"file":"\/var\/www\/html\/embassy\/vendor\/dingo\/api\/src\/Http\/FormRequest.php","class":"Dingo\\Api\\Exception\\ValidationHttpException","trace":["#0 \/var\/www\/html\/embassy\/vendor\/laravel\/framework\/src\/Illuminate\/Validation\/ValidatesWhenResolvedTrait.php(25): Dingo\\Api\\Http\\FormRequest->failedValidation

我使用该功能的方式

    let p = ["title" : "a",

                         "propertyId":"1",

                         "description":"hey",

                         "userId":"131",

                         "params":"mobile"

                ]
NetworkRequest.sharedInstance.sendImageWithParams(imageView.image!, url: "http://52.66.131.92/api/blogs", photoParamKey: "photo", params: p, getResponse: { (success, error) in
                    print("Error:\(error)")
                    print("Success:\(success)")
                })

P.S - &gt;我正确发送所有参数!。

1 个答案:

答案 0 :(得分:0)

您要么输入错误的API端点或传递错误的参数,因为在您的代码中,您尝试上传图片,但API端点需要userIdpropertyId,{{ 1}}和title是接受图像的必要参数。我无法在您的请求中看到这些值。