使用 Alamofire 4 swift 3 上传图像
Posted
技术标签:
【中文标题】使用 Alamofire 4 swift 3 上传图像【英文标题】:Uploading image with Almofire 4 swift 3 【发布时间】:2016-11-28 23:38:38 【问题描述】:我想用 almofire 将照片上传到服务器我现在正在使用此代码,但我正在超时
let imageData = UIImageJPEGRepresentation(croppedImage, 1)
let urlRequest = self.urlRequestWithComponents(url, imageData: imageData!)
self.alamofire.upload(urlRequest.1, to: urlRequest.0 as! URLConvertible).responseJSON response in
guard response.result.isSuccess else
self.showError()
return
guard let data = response.result.value else
self.showError()
return
let json = JSON(data)
func urlRequestWithComponents(_ urlString:String, imageData:Data) -> (URLRequestConvertible, Data)
var urlRequest = URLRequest(url: URL(string: urlString)!)
urlRequest.httpMethod = HTTPMethod.post.rawValue
let boundary = generateBoundaryString()
let contentType = "multipart/form-data;boundary=" + boundary
urlRequest.setValue(contentType, forHTTPHeaderField: "Content-Type")
let uploadData = NSMutableData()
uploadData.append("\r\n--\(boundary)\r\n".data(using: String.Encoding.utf8)!)
uploadData.append("Content-Disposition: form-data; name=\"file\"; filename=\"file.png\"\r\n".data(using: String.Encoding.utf8)!)
uploadData.append("Content-Type: image/png\r\n\r\n".data(using: String.Encoding.utf8)!)
uploadData.append(imageData)
uploadData.append("\r\n--\(boundary)--\r\n".data(using: String.Encoding.utf8)!)
return try! (Alamofire.URLEncoding.default.encode(urlRequest, with: nil), uploadData as Data)
这个问题有解决办法吗?
【问题讨论】:
请回复我的回答。 【参考方案1】:在 swift 3 中试试这个
Alamofire.upload(multipartFormData: (multipartFormData) in
multipartFormData.append(imageData, withName: "photo_path", fileName: "swift_file.jpeg", mimeType: "image/jpeg")
, to:"http://server1/upload_img.php")
(result) in
switch result
case .success(let upload, _, _):
upload.uploadProgress(closure: (Progress) in
print("Upload Progress: \(Progress.fractionCompleted)")
)
upload.responseJSON response in
//self.delegate?.showSuccessAlert()
print(response.request) // original URL request
print(response.response) // URL response
print(response.data) // server data
print(response.result) // result of response serialization
// self.showSuccesAlert()
//self.removeImage("frame", fileExtension: "txt")
if let JSON = response.result.value
print("JSON: \(JSON)")
case .failure(let encodingError):
//self.delegate?.showFailAlert()
print(encodingError)
【讨论】:
"server1/upload_img.php"是你的图片位置路径还是API函数文件路径?? @Bhavin_m 不是我的 API URL以上是关于使用 Alamofire 4 swift 3 上传图像的主要内容,如果未能解决你的问题,请参考以下文章
如何在 Swift 4 中使用 Alamofire 上传具有其他参数的多个图像
text Alamofire - 使用Swift 3上传文件