使用Alamofire无法正常工作将图像上传到服务器
我想在API调用中从图库向服务器发送图像。该图像必须作为参数传递。要通过图像作为参数,我试图让图像的URL像这样,但它并没有给予正确的URL ..使用Alamofire无法正常工作将图像上传到服务器
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]
使用此功能时作出的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,然后在该函数中使用该图像 – Zee
,并且已经给出了要上传的图像的正确文件名,例如... imageFileName.jpg。但是如果我从图库中选择一张图片,那么这张图片就不会有这样一个明确的名字。那么在这种情况下我们该怎么做......? –
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在Keys.Image里面??不能使这个出来:) :) –
参数是一个包含key - >“image”的图像的dicionary,所以键是包含这些键的结构 –
https://stackoverflow.com/questions/39631823/swift-3-alamofilre-4-0-multipart-image-upload-with-progress和https://stackoverflow.com/questions/39809867/alamofire-4-upload-with-parameters – iPatel
确实经历过之前,@iPatel ...但它没有帮助... –
使用我的答案https:/ /stackoverflow.com/questions/45651187/upload-photo-file-with-json-and-custom-headers-via-swift-3-and-alamofire-4-i/46116478#46116478只需将密钥在密钥字典中传递 –