当我尝试将图像上传到服务器时出现以下错误:
Error Domain = NSCocoaErrorDomain代码= 3840“无值。” UserInfo = {NSDebugDescription =无值。}
这是我一直在使用的代码:
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
@IBOutlet var imageView: UIImageView!
@IBOutlet var myactivityindicator: UIActivityIndicatorView!
@IBAction func uploadBtn(_ sender: UIButton) {
myImageUploadRequest()
}
@IBAction func selectBtn(_ sender: UIButton) {
let myimagepicker = UIImagePickerController()
myimagepicker.delegate = self
myimagepicker.sourceType = UIImagePickerControllerSourceType.photoLibrary
self.present(myimagepicker, animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
imageView.image = info[UIImagePickerControllerOriginalImage] as? UIImage
self.dismiss(animated: true, completion: nil)
}
func myImageUploadRequest() {
let myurl = NSURL(string: "http://10.1.1.11/akash/upload_image/image.php")
let request = NSMutableURLRequest(url:myurl! as URL)
request.httpMethod = "POST"
let param = [
"firstName" : "Akash",
"lastName" : "Golui",
"userId" : "1"
]
let myboundary = generateBoundaryString()
request.setValue("multipart/form-data; boundary=\(myboundary)", forHTTPHeaderField: "Content-Type")
let imageData = UIImageJPEGRepresentation(imageView.image!, 1)
if(imageData==nil) { return; }
request.httpBody = createBodyWithParameters(parameters: param, filePathKey: "file", imageDataKey: imageData! as NSData, boundary: myboundary) as Data
myactivityindicator.startAnimating()
let task = URLSession.shared.dataTask(with: request as URLRequest) {
data, response, error in
if error != nil {
print("error=\(String(describing: error))")
return
}
// You can print out response object
print("******* response = \(String(describing: response))")
// Print out reponse body
let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
print("****** response data = \(responseString!)")
do {
let json = try JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary
print(json!)
DispatchQueue.main.async(execute: {
self.myactivityindicator.stopAnimating()
self.imageView.image = nil;
});
} catch {
print(error)
}
}
task.resume()
}
func createBodyWithParameters(parameters: [String: String]?, filePathKey: String?, imageDataKey: NSData, boundary: String) -> NSData {
let body = NSMutableData();
if parameters != nil {
for (key, value) in parameters! {
body.append(NSString(format: "--\(boundary)\r\n" as NSString,boundary).data(using: String.Encoding.utf8.rawValue)!)
body.append(NSString(format:"Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n" as NSString).data(using: String.Encoding.utf8.rawValue)!)
body.append("\(value)\r\n".data(using: String.Encoding.utf8, allowLossyConversion: true)!)
}
}
let filename = "user-profile.jpg"
let mimetype = "image/jpg"
body.append(NSString(format: "--\(boundary)\r\n" as NSString,boundary).data(using: String.Encoding.utf8.rawValue)!)
body.append(NSString(format:"Content-Disposition: form-data; name=\"\(filePathKey!)\"; filename=\"\(filename)\"\r\n" as NSString).data(using: String.Encoding.utf8.rawValue)!)
body.append(NSString(format: "Content-Type: \(mimetype)\r\n\r\n" as NSString).data(using: String.Encoding.utf8.rawValue)!)
body.append(imageDataKey as Data)
body.append(NSString(format: "\r\n").data(using: String.Encoding.utf8.rawValue)!)
body.append(NSString(format: "--\(boundary)--\r\n" as NSString,boundary).data(using: String.Encoding.utf8.rawValue)!)
return body
}
func generateBoundaryString() -> String {
return "Boundary-\(NSUUID().uuidString)"
}
}
extension NSMutableData {
func appendString(string: String) {
let data = string.data(using: String.Encoding.utf8, allowLossyConversion: true)
append(data!)
}
}