2014-11-09 2 views
1

Я следую за этим tutorial этого человека, как загрузить изображение с Xcode в локальную папку на моем компьютере.Xcode - загрузить изображение из Iphone Simulator в локальную папку с помощью PHP

Когда я компилирую и запускаю код, все в порядке, и я не получаю никаких ошибок, но изображение не находится в папке, где это должно быть.

Краткое изложение того, как программа должна работать:

  1. Пользователь выбирает изображение из своей библиотеки фотографий с помощью UIImagePicker

  2. UIImageView обновляется с UIImage, что пользователь выбрал

  3. Пользователь нажимает кнопку «загрузить», которая вызывает IBAction «uploadImage»

  4. Функция uploadImage преобразует UIImage в NSData и отправить его в PHP

  5. PHP будет загрузить изображение в выберите папку

Код для IBAction «uploadImage»

-(IBAction)uploadImage{ 

//this is the url where the PHP file is located 
NSString *urlString = @"http://localhost/~andy/uploadimage.php"; 

//Convert selected UIImage to NSData 
NSData *imageData = UIImageJPEGRepresentation(chosenImage,.3); 

if (imageData != nil) 
{ 
    NSString *filenames = [NSString stringWithFormat:@"imageUploaded"];  

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

    NSString *boundary = @"---------------------------14737809831466499882746641449"; 
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary]; 
    [request addValue:contentType forHTTPHeaderField: @"Content-Type"]; 

    NSMutableData *body = [NSMutableData data]; 

    [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]]; 
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"filenames\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]]; 
    [body appendData:[filenames dataUsingEncoding:NSUTF8StringEncoding]]; 
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]]; 

    //I use a method called randomStringWithLength: to create a unique name for the file, so when all the aapps are sending files to the server, none of them will have the same name: 
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"userfile\"; filename=\"%@.jpg\"\r\n",[self randomStringWithLength:10]] dataUsingEncoding:NSUTF8StringEncoding]]; 
    [body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]]; 
    [body appendData:[NSData dataWithData:imageData]]; 
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]]; 

    [request setHTTPBody:body]; 

    NSOperationQueue *queue = [[NSOperationQueue alloc] init]; 

    //Run code async 
    [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) 
    { 
     NSData *returnData = data; 
     NSLog(@"data recieved!%@", returnData); 

     //Do what you want with your return data. 
    }]; 
} 
} 

Это PHP код uploadimage.php:

<?php 

$target_path = "/";  //where I want the uploaded images to go 
$target_path = $target_path . basename($_FILES['userfile']['name']); 

if(move_uploaded_file($_FILES['userfile']['tmp_name'], $target_path)) { 

    echo "Image uploaded"; 
} 
else { 

    echo "Upload Failed"; 
} 
?> 

Каталог, в котором я хочу, чтобы изображение, которое будет храниться в тот же локальный каталог, где uploadimagep.php находится в локальном хосте/~ Энди/

Результаты после запуска программы

Все возвращается успешным, но там нет изображение в моей папке в localhost/~ andy/

Кто-нибудь знает, что я делаю неправильно? Я чувствую, что где-то я совершил ошибку новобранец.

Заранее благодарен!

ответ

0

Вот пример:

#define DataDownloaderRunMode @"myapp.run_mode" 
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url 
           cachePolicy:NSURLRequestUseProtocolCachePolicy 
           timeoutInterval:60]; 
[request setHTTPMethod:@"POST"]; 
// We need to add a header field named Content-Type with a value that tells that it's a form and also add a boundary. 
// I just picked a boundary by using one from a previous trace, you can just copy/paste from the traces. 
NSString *boundary = @"----WebKitFormBoundarycC4YiaUFwM44F6rT"; 

NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary]; 
[request addValue:contentType forHTTPHeaderField: @"Content-Type"]; 
// end of what we've added to the header 
// the body of the post 
NSMutableData *body = [NSMutableData data]; 
// Now we need to append the different data 'segments'. We first start by adding the boundary. 
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]]; 

// Now append the image 
// Note that the name of the form field is exactly the same as in the trace ('attachment[file]' in my case)! 
// You can choose whatever filename you want. 
[body appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name=\"attachment[file]\"; 
filename=\"picture.png\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]]; 
// We now need to tell the receiver what content type we have 
// In my case it's a png image. If you have a jpg, set it to 'image/jpg' 
[body appendData:[[NSString stringWithString:@"Content-Type: image/png\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]]; 
// Now we append the actual image data 
[body appendData:[NSData dataWithData:imageData]]; 
// and again the delimiting boundary  
[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]]; 

// adding the body we've created to the request 
[request setHTTPBody:body]; 
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request 
                 delegate:self 
                 startImmediately:NO]; 
[connection scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:DataDownloaderRunMode]; 
[connection start];