在UIKit 就有提供功能很強大的class讓我們使用可以自訂HTTP Request的格式
讓我們可以傳送http request給server
接下來我們會用到幾個class
NSURL, NSMutableURLRequest, NSURLConnection
有關HTTP基本的知識,請參考
在iOS 手持式裝置中我們就是要用上面提到的Class來自訂
自已的Post Request並且把file 轉成NSData傳到server,要記得,要傳到遠端的東西都要轉成NSData
先來看看怎麼把file轉成NSData
============================
NSString * filePath = @"/Users/macuser/Desktop/back.png";
NSData *fileContent = [NSData dataWithContentsOfFile:filePath options:0 error:nil];
============================
很簡單地利用NSData的 dataWithContentsOfFile:options:error: 這個method把file轉成NSData
在這裡是利用simulator來拿桌面上的file,真正放到iOS裝置上時,要用合法位置的檔案
再來就是自訂POST Request的部分
============================
-(void) uploadBinary:(NSData * ) binary withURL:(NSString * ) urlAddress withAttName:(NSString *) attname andFilename:(NSString *) filename{
NSURL *theURL = [NSURL URLWithString:urlAddress];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:theURL
cachePolicy:NSURLRequestReloadIgnoringCacheData
timeoutInterval:20.0f];
[theRequest setHTTPMethod:@"POST"];
NSString *boundary = [[NSProcessInfo processInfo] globallyUniqueString];
NSString *boundaryString = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
[theRequest addValue:boundaryString forHTTPHeaderField:@"Content-Type"];
// define boundary separator...
NSString *boundarySeparator = [NSString stringWithFormat:@"--%@\r\n", boundary];
//adding the body...
NSMutableData *postBody = [NSMutableData data];
[postBody appendData:[boundarySeparator dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\n",attname, filename] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:binary];
[postBody appendData:[[NSString stringWithFormat:@"\r\n--%@--\r \n",boundary]
dataUsingEncoding:NSUTF8StringEncoding]];
[theRequest setHTTPBody:postBody];
[[[NSURLConnection alloc] initWithRequest:theRequest delegate:self] autorelease];
}
============================
綠色的部分是Header,藍色的部分是Post body,其中boundary的部分都不能省略
[theRequest setHTTPMethod:@"POST"];是設定POST Method
NSString *boundaryString = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
[theRequest addValue:boundaryString forHTTPHeaderField:@"Content-Type"];設定 Type
整個BODY都要用NSData傳出去,所以要宣告一個NSMutableData
@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\n",attname, filename
這一串是和Server說,POST的Key要叫做attname,這個file的名字要放在 filename(上列右邊)這個變數而server是用"filename"這個key把filename的值取出來
沒有留言:
張貼留言