我试图发送一个图像(从用户使用UIImagePickerController),到一个正在寻找物理文件的API。 JPEG或PNG都可以...使用此代码...我如何格式化它以发送?通过HTTPS POST发送图像?
我的POST功能......的“(图像变量)”中的postString应该是图像文件...
var request = URLRequest(url: URL(string: "web address.php")!)
request.httpMethod = "POST"
let postString = "action=setDefendentData&username=\("\(userNameString!)")&datetime=\(localDate)&latitude=\(latitude!)&longitude=\(longitude!)&image=\(image variable)"
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
OperationQueue.main.addOperation{
loginAlertPopup(title: "Error", message: "Invalid Source: Check Internet Connection")
}
// check for fundamental networking error
print("error=\(error)")
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
let responseString = String(data: data, encoding: .utf8)
if responseString! == "success" {
print("Good")
// Success Alert \\
self.presentAlert(title: "Success", message: "Check-In has been updated!")
}
if responseString! == "fail" {
print("failed sending image")
print("Post String: \(postString)")
// Alert Error \\
OperationQueue.main.addOperation{
self.presentAlert(title: "Error", message: "Failed Sending Data")
}
}
}
task.resume()
}
这是我的代码保存使用的UIImagePickerController的图像数据:
let fileDirectory : NSURL = {
return try! FileManager.default.url(for: .documentDirectory , in: .userDomainMask , appropriateFor: nil, create: true)
}() as NSURL
let imageQuality: CGFloat = 0.5
let image = info[UIImagePickerControllerOriginalImage] as! UIImage
// Saves to App Data
let imagePath = fileDirectory.appendingPathComponent("uploadImage.jpg")
guard let imageData = UIImageJPEGRepresentation(image, imageQuality) else {
// handle failed conversion
presentAlert(title: "Error", message: "Image Failure")
print("jpg error")
return
}
try! imageData.write(to: imagePath!)
print("Image Path: \(imagePath!)")
print("Image Size: \(imageData)")
//Get Image
let documentPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
if let dirPath = documentPath.first{
let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent("uploadImage.jpg")
let newImage = UIImage(contentsOfFile: imageURL.path)
我试过发送通过image
变量(在这种情况下为newImage
),它不接受它。我在我的视图控制器上创建了一个临时UIImageView来显示newImage
,并相应地进行了更新... API处理程序不接受它。
任何信息/帮助吗?
http://stackoverflow.com/questions/16434537/post-image-to-server-in-iphone图像 –