как изменить nsdata uiimage в двоичные данные для отправки в php - PullRequest
1 голос
/ 06 марта 2012

Сначала я показываю свой связанный код:

, преобразующий UIImage в NSData:

 imageData = UIImagePNGRepresentation(myImage);

Затем я написал NSMutableRequest:

NSString *urlString = @"http://136.206.46.10/~katie_xueke/test.php";

NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init]autorelease];
[request setURL:[NSURL URLWithString:urlString]];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:30.0f];

[request setHTTPMethod:@"POST"];

Затем я написал NSMutableData:

NSString *boundary = [NSString stringWithString:@"---------------------------14737809831466499882746641449"];
NSMutableData *body = [NSMutableData data];

//Image
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name =\"image\";filename=\"%@\"\r\n",imageName] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:@"Content-Type:application/octet-stream\r\n\r\n"]dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Length: %@\r\n",postLength]dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
[body appendData:[[NSString stringWithFormat:@"--%@--",boundary] dataUsingEncoding:NSUTF8StringEncoding]];

$$ Вопрос: NSData, похоже, не может отправить на серверную часть, а часть тела, показанная в окне консоли, выглядит следующим образом:

Content-Disposition: form-data; name ="image";filename="2012:03:06 15:06:48"

Content-Type:application/octet-stream



Content-Length: 164692

‰PNG

Какпреобразовать nsdata uiimage в двоичные данные для отправки в php ??

PS: я попробовал метод Uint8

UInt8 *rawData = [imageData bytes];

Но, похоже, iOS 5 устарела.

На стороне php:

$uploaddir = './upload/';    
echo "recive a image";    
$file = basename($_FILES['userfile']['name']);    
$uploadfile = $uploaddir . $file;    

if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {    
    echo "/uploads/{$file}";    

}

Я скопировал его из какого-то другого места, и я не знаю, как показать свое POST-изображение на веб-странице.

Кто-нибудь может мне помочь?

Большое спасибо.

1 Ответ

2 голосов
/ 07 марта 2012

Наконец-то я сам нашел решение.

AFHTTPClient *client= [AFHTTPClient clientWithBaseURL:[NSURL URLWithString:@"http://XXXX"]];
NSMutableURLRequest *myRequest = [client multipartFormRequestWithMethod:@"POST" path:@"upload.php" parameters:nil constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
    [formData appendPartWithFileData:imageData name:@"uploadedfile" fileName:dateTime mimeType:@"images/png"];
}];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:myRequest];
[operation setUploadProgressBlock:^(NSInteger bytesWritten, NSInteger totalBytesWritten, NSInteger totalBytesExpectedToWrite) {

    NSLog(@"Sent %d of %d bytes", totalBytesWritten, totalBytesExpectedToWrite);

}];
[operation setCompletionBlock:^{
    NSLog(@"response string: %@", operation.responseString); //Lets us know the result including failures
}];

NSOperationQueue *queue = [[[NSOperationQueue alloc] init] autorelease];
[queue addOperation:operation];

Я использовал AFNetworking вместо ASIHttpRequest.

На стороне php мой код:

<?php

$filename="uploaded";
$target_path = "uploads/";

$target_path = $target_path . basename( $_FILES['uploadedfile']['name']); 

if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
    echo "The file ".  basename( $_FILES['uploadedfile']['name']).
    " has been uploaded";
} else{
    echo "There was an error uploading the file, please try again!";
}
?>

И спасибо, ребята, которые помогли мне.

PS: Большое спасибо за этого человека, который действительно помог мне в этом: http://6foot3foot.com/developer-journal/afnetworking-php

...