使用 Alamofire 将图像上传到服务器不起作用
Posted
技术标签:
【中文标题】使用 Alamofire 将图像上传到服务器不起作用【英文标题】:Uploading an image to server using Alamofire not working 【发布时间】:2017-10-09 08:56:00 【问题描述】:我想通过 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”)
但这也是崩溃的。我已经有这个问题很长一段时间了......无法弄清楚确切的解决方案是什么......希望有人能提供帮助...... :) 也确实经历了很多类似的问题。但是一直找不到解决办法……
编辑:我的参数是:
let Parameters =
[
"access_token": commonVarForAccessToken,
"seller_id": idForNewOldUser,
"product_id": self.productId,
"is_default": "1",
"sequence": 1,
"image": self.localPath
] as [String : Any]
【问题讨论】:
***.com/questions/39631823/… 和 ***.com/questions/39809867/… 之前确实经历过,@iPatel...但这没有帮助... 使用我的答案***.com/questions/45651187/… 只需将您的图像用键传递到字典中 我很困惑是否可以在我的场景中使用它......?你的意见是什么,@JitendraModi ? 很容易实现,只需要声明一个上面和下面的类就是那个类的使用。 【参考方案1】:带图像的 Almofire:-
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
【讨论】:
..Keys.Image 中的 Keys 是什么...?无法弄清楚...:) parameters 是一个字典,其中包含一个带有 key ->"image" 的图像,所以 keys 是一个包含这些键的结构【参考方案2】:首先使用该函数进行 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)")
【讨论】:
感谢@Zee,但我从图库中挑选了图片。那么该图像不应该先转换为它的网址吗...? 您可以从图库中选择图像并将其分配给 UIImageView,然后在该功能中使用它 另外,您已经为要上传的图像提供了正确的文件名,如下所示...imageFileName.jpg。但是,如果我从图库中选择一张图片,那么该图片将没有如此明确的名称。那么在这种情况下我们该怎么办...? 这是可选的,这不是我的图像文件名。 变量命名(数据)将定义一切以上是关于使用 Alamofire 将图像上传到服务器不起作用的主要内容,如果未能解决你的问题,请参考以下文章