我试图使用带有swift的php文件将照片插入数据库,但我只能将照片添加到htdocs下的文件中'上传'但是我无法添加数据库的路径。 有人可以告诉我如何将参数照片添加到数据库中,并且知道我已经使用过本教程: http://swiftdeveloperblog.com/image-upload-example/
这是我的代码:
斯威夫特
// UploadViewController.swift
import UIKit
class UploadViewController: UIViewController,UIImagePickerControllerDelegate,UINavigationControllerDelegate
{
@IBOutlet weak var myActivityIndicator: UIActivityIndicatorView!
@IBOutlet weak var myImageView: UIImageView!
@IBAction func uploadButtonTapped(sender: AnyObject) {
//my Image upload
myImageUploadRequest()
}
override func viewDidLoad() {
super.viewDidLoad()
let defaults = NSUserDefaults.standardUserDefaults();
print("fffffff" + defaults.stringForKey("abc")!)
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func selectPhotoButtonTapped(sender: AnyObject) {
var myPickerController = UIImagePickerController()
myPickerController.delegate = self;
myPickerController.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
self.presentViewController(myPickerController, animated: true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject])
{
myImageView.image = info[UIImagePickerControllerOriginalImage] as? UIImage
self.dismissViewControllerAnimated(true, completion: nil)
}
func myImageUploadRequest()
{
let myUrl = NSURL(string: "http://localhost:8888/Swift/my-http-post-example.php");
//let myUrl = NSURL(string: "http://www.boredwear.com/utils/postImage.php");
let request = NSMutableURLRequest(URL:myUrl!);
request.HTTPMethod = "POST";
let param = [
"firstName" : "Sergey",
"lastName" : "Kargopolov",
"userId" : "9"
]
let boundary = generateBoundaryString()
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
let imageData = UIImageJPEGRepresentation(myImageView.image!, 1)
if(imageData==nil) { return; }
request.HTTPBody = createBodyWithParameters(param, filePathKey: "file", imageDataKey: imageData!, boundary: boundary)
myActivityIndicator.startAnimating();
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil {
print("error=\(error)")
return
}
// You can print out response object
print("******* response = \(response)")
// Print out reponse body
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("****** response data = \(responseString!)")
var err: NSError?
do {
var json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSDictionary
dispatch_async(dispatch_get_main_queue(),{
self.myActivityIndicator.stopAnimating()
self.myImageView.image = nil;
});
}
catch let error as NSError {
print("An error occurred: \(error)")
}
}
task.resume()
}
func createBodyWithParameters(parameters: [String: String]?, filePathKey: String?, imageDataKey: NSData, boundary: String) -> NSData {
var body = NSMutableData();
if parameters != nil {
for (key, value) in parameters! {
body.appendString("--\(boundary)\r\n")
body.appendString("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
body.appendString("\(value)\r\n")
}
}
// defaults.setValue(String("0"), forKey: "abc")
let defaults = NSUserDefaults.standardUserDefaults()
if ((defaults.stringForKey("abc")!) == ""){
defaults.setValue(String("0"), forKey: "abc")
}
let filename = (defaults.stringForKey("abc")!)+".jpg"
defaults.setValue(String(Int((defaults.stringForKey("abc")!))!+1), forKey: "abc")
// let defaults = NSUserDefaults.standardUserDefaults();
//let filename = "user-profile.jpg"
let mimetype = "image/jpg"
body.appendString("--\(boundary)\r\n")
body.appendString("Content-Disposition: form-data; name=\"\(filePathKey!)\"; filename=\"\(filename)\"\r\n")
body.appendString("Content-Type: \(mimetype)\r\n\r\n")
body.appendData(imageDataKey)
body.appendString("\r\n")
body.appendString("--\(boundary)--\r\n")
return body
}
func generateBoundaryString() -> String {
return "Boundary-\(NSUUID().UUIDString)"
}
}
extension NSMutableData {
func appendString(string: String) {
let data = string.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
appendData(data!)
}
}
这里是我无法在数据中插入照片的PHP文件
<?php
$firstName = $_POST["firstName"];
$lastName = $_POST["lastName"];
$userId = $_POST["userId"];
$target_dir = "uploads/";if(!file_exists($target_dir))
{
mkdir($target_dir, 0777, true);
}
$target_dir = $target_dir . "/" . basename($_FILES["file"]["name"]);
if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_dir))
{
echo json_encode([
"Message" => "The file ". basename( $_FILES["file"]["name"]). " has been uploaded.",
"Status" => "OK",
"userId" => $_REQUEST["userId"]
]);
} else {
echo json_encode([
"Message" => "Sorry, there was an error uploading your file.",
"Status" => "Error",
"userId" => $_REQUEST["userId"]
]);
}
?>