2014-11-29 4 views
1

У меня вопрос. Я искал его в Интернете, но не нашел хорошего ответа.iOS загрузить image php + mysql

Мне нравится загружать изображение в таблицу mysql, поле longblob. Я также должен получить некоторые данные для публикации. (Имя пользователя и пароль и прочее).

Я хочу сделать это из приложения iOS в xCode. Так у кого-то есть код, который я должен реализовать на стороне iOS и на стороне сервера (php)?

+0

с использованием стандартного html (5) будет работать на всех основных баузерах и iOS. Единственное, что может быть конкретным - это css, чтобы хорошо отображать вещи на мобильном устройстве (так же отзывчивое) см. Здесь http://www.codepool.biz/tech-frontier/html5/take-a-photo-and- upload-it-on-mobile-phones-with-html5.html с некоторыми дополнительными, такими как , который позволяет загружать непосредственно с камеры телефона –

+0

Да, но я хочу сделать это в приложении, я добавлю его на вопрос –

+0

запустите приложение в html;) что должно делать приложение? Приложения iOS имеют полный доступ к протоколу сокетов/http, но делают вещи более сложными, чем простой html. –

ответ

0

Итак, у меня есть этот код сейчас, но он, похоже, не работает.

<?php 
require_once("Database.php"); 
$con = getConnection(); 
session_start(); 

$email = $_POST['email']; 

$contact = $_POST['contactID']; 
$password = $_POST['password']; 

$email = stripslashes($email); 
$contact = stripslashes($contact); 
$password = stripslashes($password); 
$password = md5($password); 
$sql="SELECT ID FROM User WHERE email='$email' AND password='$password'"; 
$result=mysql_query($sql); 

// Mysql_num_row is counting table row 
$count=mysql_num_rows($result); 
// If result matched $myusername and $mypassword, table row must be 1 row 

//echo $id ." <br/>"; 
//echo $count; 

if($count==1) { 
    $row = mysql_fetch_object($result); 
    $id = $row->ID; 

} 
// Make sure the user actually 
// selected and uploaded a file 
if (isset($_FILES['image']) && $_FILES['image']['size'] > 0) { 

    // Temporary file name stored on the server 
    if (move_uploaded_file($_FILES['image']['tmp_name'], $uploadfile)) { 
     echo "File is valid, and was successfully uploaded.\n"; 
    } else { 
     echo "Possible file upload attack!\n"; 
    } 


} else { 
    print "No image selected/uploaded"; 
} 


?> 

для моего файла php. И для моей загрузки xcode:

-(void) uploadImage: (SparkContact *) contact 
{ 
    NSString *type = @"upload"; 
    NSString *email = self.fileController.user.email; 
    NSString *password = self.fileController.user.password; 
    UIImage *image = [[UIImage alloc] initWithData:contact.image]; 
    NSData *data = UIImagePNGRepresentation(image); 
    NSString *post = 
    [[NSString alloc] initWithFormat:@"&email=%@&password=%@&contactID=%@&image=%@",email,password,contact.userid,data]; 

    NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]; 

    NSString *postLength = [NSString stringWithFormat:@"%d", (int)[postData length]]; 

    NSURL *url = [NSURL URLWithString:@"http://spark-app.freeiz.com/addImage.php"]; 
    NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url]; 
    [theRequest setHTTPMethod:@"POST"]; 
    [theRequest setValue:postLength forHTTPHeaderField:@"Content-Length"]; 
    [theRequest setHTTPBody:postData]; 


    ContactSyncObject *obj = [[ContactSyncObject alloc] initWithType:type withContact:contact]; 
    obj.fileController = self.fileController; 
    [obj startSync:theRequest]; 
} 

И контактыyncobject выполняет запрос, отправляющий и обрабатывающий ответ. Но ответ я получаю: "Изображение не выбрано/закачано"

+0

выглядит так, как загруженное изображение кодируется в $ _post ['image'] в ascii и не обрабатывается как загруженный файл (например, при загрузке файла с помощью html-формы), вам придется адаптировать php-код для создания файла из $ _post ['image'], а не ссылку $ _FILE. не могу сказать, как вы вернете NSASCIIStringEncoding. Другой вариант - найти способ добавления заголовка contentType: «application/x-www-form-urlencoded», тогда я думаю, php создаст ссылку $ _FILE –

+0

, возможно, это может помочь http://stackoverflow.com/questions/20247423/ ios-http-post-data-and-image-image-not-getting-published –

+0

Спасибо вам большое! Он работал с некоторой настройкой! –

0

Это мое решение для моей проблемы

Код Objective-C:

NSString *email = self.fileController.user.email; 
NSString *password = self.fileController.user.password; 
UIImage *image = [[UIImage alloc] initWithData:contact.image]; 
if(image == nil){ 
    //UNKNOWN IMAGE 
    //image = [UIImage imageNamed:@"unknown.png"]; 
    return; 
} 

//The $_POST parameters you want to add 
NSDictionary *params = @{ @"email": email, @"contact": contact.userid, @"password": password }; 
//The image to data 
NSData *imageData = UIImagePNGRepresentation(image); 
//your url 
NSString *urlString = @"http://spark-app.freeiz.com/addImage.php"; 


NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; 
[request setURL:[NSURL URLWithString:urlString]]; 
[request setHTTPMethod:@"POST"]; 

NSString *boundary = @"0xKhTmLbOuNdArY"; 
NSString *kNewLine = @"\r\n"; 

// Note that setValue is used so as to override any existing Content-Type header. 
// addValue appends to the Content-Type header 
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary]; 
[request setValue:contentType forHTTPHeaderField: @"Content-Type"]; 

NSMutableData *body = [NSMutableData data]; 

// Add the parameters from the dictionary to the request body 
for (NSString *name in params.allKeys) { 
    NSData *value = [[NSString stringWithFormat:@"%@", params[name]] dataUsingEncoding:NSUTF8StringEncoding]; 

    [body appendData:[[NSString stringWithFormat:@"--%@%@", boundary, kNewLine] dataUsingEncoding:NSUTF8StringEncoding]]; 
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"", name] dataUsingEncoding:NSUTF8StringEncoding]]; 
    // For simple data types, such as text or numbers, there's no need to set the content type 
    [body appendData:[[NSString stringWithFormat:@"%@%@", kNewLine, kNewLine] dataUsingEncoding:NSUTF8StringEncoding]]; 
    [body appendData:value]; 
    [body appendData:[kNewLine dataUsingEncoding:NSUTF8StringEncoding]]; 
} 

// Add the image to the request body 
[body appendData:[[NSString stringWithFormat:@"--%@%@", boundary, kNewLine] dataUsingEncoding:NSUTF8StringEncoding]]; 
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"myPngFile.png\"%@", @"image", kNewLine] dataUsingEncoding:NSUTF8StringEncoding]]; 
[body appendData:[[NSString stringWithFormat:@"Content-Type: image/png"] dataUsingEncoding:NSUTF8StringEncoding]]; 
[body appendData:[[NSString stringWithFormat:@"%@%@", kNewLine, kNewLine] dataUsingEncoding:NSUTF8StringEncoding]]; 
[body appendData:imageData]; 
[body appendData:[kNewLine dataUsingEncoding:NSUTF8StringEncoding]]; 

// Add the terminating boundary marker to signal that we're at the end of the request body 
[body appendData:[[NSString stringWithFormat:@"--%@--", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; 

[request setHTTPBody:body]; 
//Now start the request (asynchronous or synchronous) 

Код PHP: // изменить к пути должно быть $ uploadfile = "путь к новому изображению". ".png | .jpg | ...";

// selected and uploaded a file 
if (isset($_FILES['image']) && $_FILES['image']['size'] > 0) { 



    // Temporary file name stored on the server 

    if (move_uploaded_file($_FILES['image']['tmp_name'], $uploadfile)) { 

     echo "File is valid, and was successfully uploaded.\n"; 

    } else { 

     echo "Possible file upload attack!\n"; 

    } 





} else { 

    print "No image selected/uploaded"; 

} 
+0

Это весь PHP-код? –