使用Alamofire无法正常将图像上传到服务器

时间:2017-10-09 08:56:00

标签: ios swift alamofire

我想在API调用中将图像从库发送到服务器。该图像必须作为参数传递。要将图像作为参数传递,我试图获取图像的url,但它没有给出正确的URL ..

var selectedImage : UIImage = image
let imageData: NSData = UIImagePNGRepresentation(selectedImage)! as NSData
let imageStr = imageData.base64EncodedString(options:.endLineWithCarriageReturn)
imageArray.append(image)

此外,我尝试上传图片......

        for img in imageArray {

            let url = "http://myApp..com/a/images_upload"
            let headers = [ "Content-Type":"application/x-www-form-urlencoded"]

            let URL = try! URLRequest(url: url, method: .post, headers: headers)
            let parameters =
                [
                    "access_token": accessToken
                    "image": img
                    ] as [String : Any]


            let imgData = UIImageJPEGRepresentation(img, 0.2)!

            Alamofire.upload(multipartFormData: { (multipartFormData) in
                multipartFormData.append(imgData, withName: "image",fileName: "file.jpg", mimeType: "file")
                for (key, value) in parameters {
                    multipartFormData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key)
                }
            }, with: URL) { (result) in
                switch result {
                case .success(let upload, _, _):

                    upload.uploadProgress(closure: { (progress) in
                        print("Upload Progress: \(progress.fractionCompleted)")
                    })

                    upload.responseJSON { response in
                        print(response.result.value)
                        if let value = response.result.value {                                
                            print("IMG UPLOADED!!!")
                        }
                    }
                    case .failure(let encodingError):
                    print(“ERROR”)
}}}

但这也是崩溃。我已经有这个问题已经有一段时间了......不知道具体的解决方案是什么......希望有人可以提供帮助... :)也确实在SO上经历了很多类似的问题。但直到......才找到解决方案。

编辑:我的参数是:

let Parameters =
                    [
                        "access_token": commonVarForAccessToken,
                        "seller_id": idForNewOldUser, 
                        "product_id": self.productId,
                        "is_default": "1",
                        "sequence": 1,
                        "image": self.localPath
                        ] as [String : Any]

2 个答案:

答案 0 :(得分:0)

首先使用此函数进行URLRequest。

 func makeUrlRequestWithComponents(urlString:String, parameters:Dictionary<String, Any>, imageData:NSData) -> (URLRequestConvertible, NSData) {

// create url request to send
let mutableURLRequest = NSMutableURLRequest(URL: NSURL(string: urlString)!)
mutableURLRequest.HTTPMethod = Alamofire.Method.POST.rawValue
let boundaryConstant = "myRandomBoundary12345";
let contentType = "multipart/form-data;boundary="+boundaryConstant
mutableURLRequest.setValue(contentType, forHTTPHeaderField: "Content-Type")



// create upload data to send
let uploadData = NSMutableData()

// add image
uploadData.appendData("\r\n--\(boundaryConstant)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
uploadData.appendData("Content-Disposition: form-data; name=\"file\"; filename=\"file.png\"\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
uploadData.appendData("Content-Type: image/png\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
uploadData.appendData(imageData)

// add parameters
for (key, value) in parameters {
    uploadData.appendData("\r\n--\(boundaryConstant)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
    uploadData.appendData("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n\(value)".dataUsingEncoding(NSUTF8StringEncoding)!)
}
uploadData.appendData("\r\n--\(boundaryConstant)--\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)



// return URLRequestConvertible and NSData
return (Alamofire.ParameterEncoding.URL.encode(mutableURLRequest, parameters: nil).0, uploadData)
 }

然后这是上传图片的功能。

func uploadImage()
{

    let Parameters =
   [
"access_token": commonVarForAccessToken,
"seller_id": idForNewOldUser,
"product_id": self.productId,
"is_default": "1",
"sequence": 1,
] as [String : Any]


// example image data

let imageData = UIImagePNGRepresentation(myImageView.image!,1)



// CREATE AND SEND REQUEST ----------

 let urlRequest = makeUrlRequestWithComponents("http://myApp..com/a/images_upload", parameters:      parameters, imageData: imageData)

  Alamofire.upload(urlRequest.0, urlRequest.1).progress { (bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) in
    println("\(totalBytesWritten) / \(totalBytesExpectedToWrite)")
}
.responseJSON { (request, response, JSON, error) in
    println("REQUEST \(request)")
    println("RESPONSE \(response)")
    println("JSON \(JSON)")
    println("ERROR \(error)")
  }
 }

答案 1 :(得分:0)

Almofire With Image: -

Alamofire.upload(multipartFormData: { (multipartFormData) in
            print(parameters)
            if Array(parameters.keys).contains(Keys.Image) {
            multipartFormData.append(UIImageJPEGRepresentation((parameters)[Keys.Image] as! UIImage, 1)!, withName: "image", fileName: "swift_file.jpeg", mimeType: "image/jpeg")
            }
            for (key, value) in parameters {
                print(key,value)
                if key != Keys.Image{
                multipartFormData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key)
                }
            }
        }, to:url)
        { (result) in
            switch result {
            case .success(let upload, _, _):
                upload.uploadProgress(closure: { (progress) in
                    //Print progress
                })
                upload.responseJSON { response in
                    print(response.result)
                    self.getValidDict(result: response.result, completion: { (dict, error) in
                        var dict = dict
                        print(dict!)
                        print(parameters)
                        if dict == nil {
                            dict = NSDictionary.init(dictionary:
                                [kResultMessageKey: error?.localizedDescription ?? "Some error has been occured",
                                 kResultStatusKey: false])
                        }
                           Completion(true,dict![Keys.result]! as AnyObject)
                    })
               }
            case .failure(let encodingError):
                //print(encodingError.description)
                Completion(false,encodingError.localizedDescription as AnyObject)
                break
            }
        }