Saturday, June 12, 2010

[iPhone] image, photo upload to php

There are two ways to tackle this issue. One we can base64 encode the file and post is normally inside a XML or JSON instance or we can simulate a normal HTML post. This tutorial will go over the HTML post출처: Post a UIImage to the web : Iphone Noob

뭐 여러 방법이 있다고 한다...


1. php 페이지

whatsit is 
MAX_FILE_SIZE is 
Upload: 
Type: 
Size: 
Stored: 
not uploaded

Please upload a new picture and title

Please enter the title of that picture: 
Please choose an image to upload: 
then: 


위와 같은 구성에 대한 코드는 다음과 같다.

<?

 move_uploaded_file($_FILES['imagefile']['tmp_name'],"./img/latest.jpg") 

 $instr = fopen("./img/latest.jpg","rb");

 $image = mysql_real_escape_string(fread($instr,filesize("./img/latest.jpg")));

    mysql_query ("insert into pix (title, imgdata) values (\"".

                $_REQUEST[whatsit].

                "\", \"".

                $image.

                "\")");

?>

<html><head>

<title>Upload an image to a database</title>

<body bgcolor=white>

<h2>Please upload a new picture and title</h2>

<form enctype=multipart/form-data method=post>

Please enter the title of that picture: <input name=whatsit><br>

Please choose an image to upload: <input type=file name=imagefile><br>

then: <input type=submit></form><br><br>

</body>

</html>


2. HTML 폼

<form> 태그의 encrype 속성은 폼을 전송할때 어떤 content-type(전송될 개체의 형태)을 사용할지 지정합니다. "multipart/form-data"는 파일의 내용과 같은 바이너리 데이터를 업로드해야 할때 사용합니다.
<input> 태그의 type="file" 속성은 입력되는 것이 파일임을 지정합니다. 예를들어, 브라우저에서 보면 텍스트 박스 하나와 찾아보기 버튼이 그 옆에 하나있을 겁니다.출처: [PHP 고급] PHP 파일 업로드 :: 컴퓨터를 사랑하는 Sirjhswin의 티스토리 블로그

<input> 태그는
type 없이 <input name=whatsit> 으로 사용자 입력 부분을 만들 수 있고...
file type을 통해 <input type=file name=imagefile> 으로 파일선택 버튼을 보여줄 수 있다.

이 두가지가 실제로 서버에 전달되는 포맷은 다음과 같다.

For normal input:

<hex value>CRLFContent-Disposition: form-data; name="<inputname>"CRLFCRLF<input value>CRLF


For file type input:

<hex value>CRLFContent-Disposition: form-data; name="<inputname>"; filename="<filepath>"CRLFContent-Type: <mime-type>CRLFCRLF<inputvalue>CRLF


출처: Pass parameters to web-service with image uploading in iphone | ASP.NET, Sharepoint, C#, VB.NET Solutions


 시작과 끝의 boundary
-----------------------------14737809831466499882746641449
-----------------------------14737809831466499882746641449--

를 추가한 실제 포맷의 예는 다음과 같다.

-----------------------------14737809831466499882746641449
Content-Disposition: form-data; name="whatsit"

Mywhatsit
-----------------------------14737809831466499882746641449
Content-Disposition: form-data; name="imagefile"; filename="myImage.jpg"
Content-Type: application/octet-stream

(Binary Content)
-----------------------------14737809831466499882746641449--


3. iPhone


출처: Post a UIImage to the web : Iphone Noob


 위와 같이 UIImageView를 Interface Builder로 끌어오고 RoundedRect 버튼도 끌어온 담에

헤더 파일에 추가해주고 이벤트와 연결해 줘야 할터...

상세한 내용은...


4. iPhone - header

  1. // setting up the request object now  
  2.  NSURL *nsurl =[NSURL URLWithString:urlString];  
  3.  NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:nsurl cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];   
  4.  [request setURL:nsurl];  
  5.  [request setHTTPMethod:@"POST"];

5. iPhone - 시작 boundary

 시작 boundary는 request에 포함되어야 하고... 이후는 body에 있어야 하는 모양이다.

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

6. iPhone - body

  1.  /* 
  2.   now lets create the body of the post 
  3.   */  
  4.  NSMutableData *body = [NSMutableData data];  
  5.    
  6.  //whatsit  
  7.  [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];   
  8.  [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"parameter1\"\r\n\r\n%@", @"whatsit"] dataUsingEncoding:NSUTF8StringEncoding]];  
  9.  [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];  

  10.  
  11.  //Image  
  12.  [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"image\"; filename=\"%@\"\r\n",[fileName text]] dataUsingEncoding:NSUTF8StringEncoding]];  
  13.  [body appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];  
  14.  [body appendData:[NSData dataWithData:imageData]];  
  15.  [body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];  

7. iPhone - set body & sendSynchronousRequest

  1.  // setting the body of the post to the reqeust  
  2.  [request setHTTPBody:body];  
  3.    
  4. NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

NSLog(@"%@", [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding]);

등을 통해 확인해 보는 것이 도움이 된다.


There are two ways to tackle this issue. One we can base64 encode the file and post is normally inside a XML or JSON instance or we can simulate a normal HTML post. This tutorial will go over the HTML po출처: Post a UIImage to the web : Iphone Noob


No comments:

Post a Comment