我想立即使用此代码将照片上传到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)
}
有关此问题的解决方案吗?
答案 0 :(得分:9)
在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)
}
}