使用 Alamofire 上传图像的问题(将图像作为参数)
Posted
技术标签:
【中文标题】使用 Alamofire 上传图像的问题(将图像作为参数)【英文标题】:Issue with uploading an image using Alamofire(has image as a parameter) 【发布时间】:2017-10-10 07:39:56 【问题描述】:这就是我尝试使用 Alamofire 上传图片的方式。但是程序崩溃说类似...'NSInvalidArgumentException', reason: '-[_SwiftTypePreservingNSNumber dataUsingEncoding:]: unrecognized selector sent to instance...
我无法弄清楚确切的原因。这就是我提出请求的方式...
for i in 1...(imageArray.count)
for img in imageArray
let url = "http://myapp.com/a/images_upload"
let headers = [ "Content-Type":"application/x-www-form-urlencoded"]
let imageData: Data = (UIImageJPEGRepresentation(img, 0.6) as Data?)!
print(imageData)
let parameters: [String: Any] = [
"access_token": commonVarForAccessToken,
"seller_id": idForNewOldUser,
"product_id": self.productId,
"is_default": "1",
"sequence": i,
"image": imageData ]
Alamofire.upload(multipartFormData: (multipartFormData) in
print(parameters)
multipartFormData.append(imageData as Data, withName: "home-\(self.index)", fileName: "home-\(self.index)", mimeType: "image/jpeg")
for (key, value) in parameters
print(key,value)
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.request) // original URL request
if let JSON = response.result.value
print("JSON: \(JSON)")
case .failure(let encodingError):
print(encodingError)
break
希望有人可以提供帮助...谢谢...:)
【问题讨论】:
为什么要使用两次循环? 某处存在对dataUsingEncoding:
的(内部/隐藏)调用,该调用不起作用,因为该对象是(NS)Number
而不是(NS)Data
。我会说是那条线:multipartFormData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key)
。你不能在任何类型的value
上做((value as AnyObject).data(using: String.Encoding.utf8.rawValue)
。我不知道其他对象的类是什么,但"sequence": i,
应该会崩溃。
我也尝试给序列一个硬编码值“1”,但它再次崩溃,可能它不接受给定格式的图像...... imageData 只是显示为“403829 字节” ...这可能是个问题吗,@Larme ?
循环使用了两次,@AsaduzzamanShuvro 因为序列具有从图库中获取的图像数量,而另一个循环遍历每个拾取的图像...
使用我的答案***.com/questions/45651187/… 只需传递图像,如 dict.set(imgview.image, forKey:"upload1") 如果您不上传视频,则将 nil 作为参数传递 @User.bw跨度>
【参考方案1】:
尝试使用此代码。它对我有用。
let para: [String: Any]
Alamofire.upload(multipartFormData: (multipartFormData) in
for i in 0..<uploadImages.count multipartFormData.append(UIImageJPEGRepresentation(uploadImages[i], 0.3)!, withName: "image\(i)", fileName: "swift_file\(i).jpeg", mimeType: "image/jpg")
for (key, value ) in para
multipartFormData.append((value).data(using: String.Encoding.utf8)!, withName: key)
, to: apiURL)
(result) in
switch result
case .success(let upload, _,_ ):
upload.uploadProgress(closure: (progress) in
UILabel().text = "\((progress.fractionCompleted * 100)) %"
print (progress.fractionCompleted * 100)
)
upload.responseJSON response in
guard ((response.result.value) != nil) else
print(response.result.error!.localizedDescription)
return
【讨论】:
以上是关于使用 Alamofire 上传图像的问题(将图像作为参数)的主要内容,如果未能解决你的问题,请参考以下文章