Xcode — загрузить изображение из Iphone Simulator в локальную папку, используя переполнение стека

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

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

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

  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 /

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

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

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

Заранее спасибо!

1

Решение

Вот пример:

#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];
0

Другие решения

Других решений пока нет …

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector