有时候会用到图片上传或者文件上传,做法是转成Data
swift3.0 Alamofire4.4情况下,因为每个版本代码会有些偏差
你选择相册或者是拍照之后,返回的image
let imgedata = UIImagePNGRepresentation(image!)
我的做法是先保存到沙盒,第一步要做的是获取沙盒位置
let DocumentsPath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)[0] as NSString
//文件管理器
let fileManager = FileManager.default
//拷贝至沙盒中 并保存为image.png
try! fileManager.createDirectory(atPath: DocumentsPath as String, withIntermediateDirectories: true, attributes: nil)
fileManager.createFile(atPath: (DocumentsPath as String) + "/image.png", contents: imgedata, attributes: nil)
//获取Home目录
let homeDirectory = NSHomeDirectory()
let documentPath = homeDirectory + "/Documents"
do {
try fileManager.createDirectory(atPath: documentPath, withIntermediateDirectories: true, attributes: nil)
}
catch let error {
}
//得到选择后沙盒中图片的完整路径
let filePath: String = String(format: "%@%@", documentPath, "/image.png")
接下来利用Alamofire,首先得获取到要上传的文件
let lastData = NSData(contentsOfFile: filePath)
然后
let headers = ["content-type":"multipart/form-data"]
Alamofire.upload(multipartFormData: { multipartFormData in
multipartFormData.append(lastData, withName: "image(看你自己)”, fileName: filePath, mimeType: "image/png")
}
}, to: urlString(自己服务器上传的地址),headers: headers,encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { response in
if let value = response.result.value as? [String: AnyObject]{
success(value)
}
}
upload.uploadProgress { progress in
//这个是获取实时进度的,有些需要展示进度,看个人
}
case .failure(let encodingError):
failture(encodingError)
}
}
)
网友评论