iOS 파일 업로드 기능 구현
그 중에서 도 NSURLConnection 은 오랫동안 사 용 된 방식 이 고 NSURLSession 은 새로 나 온 방식 이다.
1.POST 방식 으로 업로드
POST 방식 으로 정 보 를 제출 할 때 기본적으로 사용 하 는 것 은:
*Content-Type: application/x-www-form-urlencoded.
*중국 어 를 입력 하면 post 방식 이 자동 으로 전 의 됩 니 다(애플 에서 자동 으로).
국내의 절대 다수의 사이트 에서 이런 방식 으로 파일 을 업로드 한다(바 이 너 리 파일 지원)
*Content-Type:multipart/form-data(파일 업로드)
*업로드 파일 의 크기 는 보통 2M 또는 더 작 습 니 다.
애플 에서 업로드 작업 을 하 는 것 은 매우 번거롭다.업로드 에 필요 한 문자열 형식 을 맞 춰 야 업로드 가 가능 합 니 다.(머리 까지.
 
 다른 플랫폼 에서 잘 만 든 것 은 봉 인 된 것 같 습 니 다.문자열 형식 을 스스로 맞 출 필요 가 없습니다.그래서 iOS 에 서 는 이런 식 으로 올 리 는 경우 가 드물다.
예제 코드:
#import "XNUploadFile.h" 
 
#define kTimeOut 5.0f 
 
@implementation XNUploadFile 
/**       */ 
static NSString *boundaryStr = @"--"; 
/**           */ 
static NSString *randomIDStr; 
/**   (php)   ,       */ 
static NSString *uploadID; 
 
- (instancetype)init 
{ 
 self = [super init]; 
 if (self) { 
 /**           */ 
 randomIDStr = @"itcastupload"; 
 /**   (php)   ,       */ 
 //                
 //    FireBug       
 uploadID = @"uploadFile"; 
 } 
 return self; 
} 
 
#pragma mark -     .  NSURLSession      
- (void)uploadFile:(NSString *)path fileName:(NSString *)fileName completion:(void (^)(NSString *string))completion 
{ 
 // 1. url   :          php  ,   html   
 NSURL *url = [NSURL URLWithString:@"http://localhost/new/post/upload.php"]; 
 
 // 2. request 
 NSURLRequest *request = [self requestForUploadURL:url uploadFileName:fileName localFilePath:path]; 
 
 // 3. session(  ) 
 //       ,              
 NSURLSession *session = [NSURLSession sharedSession]; 
 
 // 4.     ->            
 /** URLSession   ,            ,        */ 
 [[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { 
  
 id result = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL]; 
  
 NSLog(@"%@ %@", result, [NSThread currentThread]); 
  
 dispatch_async(dispatch_get_main_queue(), ^{ 
  if (completion) { 
  completion(@"    "); 
  } 
 }); 
 }] resume]; 
 
 // NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { 
 // 
 // id result = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL]; 
 // 
 // NSLog(@"%@ %@", result, [NSThread currentThread]); 
 // 
 // dispatch_async(dispatch_get_main_queue(), ^{ 
 //  if (completion) { 
 //  completion(@"    "); 
 //  } 
 // }); 
 // }]; 
 // 
 // // 5.      
 // [task resume]; 
} 
 
#pragma mark -      :      
/**         */ 
- (NSString *)topStringWithMimeType:(NSString *)mimeType uploadFile:(NSString *)uploadFile 
{ 
 NSMutableString *strM = [NSMutableString string]; 
 
 [strM appendFormat:@"%@%@
", boundaryStr, randomIDStr]; 
 [strM appendFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"
", uploadID, uploadFile]; 
 [strM appendFormat:@"Content-Type: %@
", mimeType]; 
 
 NSLog(@"     :%@", strM); 
 return [strM copy]; 
} 
 
/**         */ 
- (NSString *)bottomString 
{ 
 NSMutableString *strM = [NSMutableString string]; 
 
 [strM appendFormat:@"%@%@
", boundaryStr, randomIDStr]; 
 [strM appendString:@"Content-Disposition: form-data; name=\"submit\"
"]; 
 [strM appendString:@"Submit
"]; 
 [strM appendFormat:@"%@%@--
", boundaryStr, randomIDStr]; 
 
 NSLog(@"     :%@", strM); 
 return [strM copy]; 
} 
 
/**         mimeType */ 
- (NSString *)mimeTypeWithFilePath:(NSString *)filePath 
{ 
 // 1.          
 if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]) { 
 return nil; 
 } 
 
 // 2.   HTTP HEAD           
 NSURL *url = [NSURL fileURLWithPath:filePath]; 
 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; 
 
 // 3.            MimeType 
 NSURLResponse *response = nil; 
 [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:NULL]; 
 
 return response.MIMEType; 
} 
 
/**          */ 
- (NSURLRequest *)requestForUploadURL:(NSURL *)url uploadFileName:(NSString *)fileName localFilePath:(NSString *)filePath 
{ 
 // 0.        mimeType 
 NSString *mimeType = [self mimeTypeWithFilePath:filePath]; 
 if (!mimeType) return nil; 
 
 // 1.           
 NSMutableData *dataM = [NSMutableData data]; 
 [dataM appendData:[[self topStringWithMimeType:mimeType uploadFile:fileName] dataUsingEncoding:NSUTF8StringEncoding]]; 
 //                
 [dataM appendData:[NSData dataWithContentsOfFile:filePath]]; 
 [dataM appendData:[[self bottomString] dataUsingEncoding:NSUTF8StringEncoding]]; 
 
 // 2.      
 NSMutableURLRequest *requestM = [NSMutableURLRequest requestWithURL:url cachePolicy:0 timeoutInterval:kTimeOut]; 
 // 1>   HTTP     
 requestM.HTTPMethod = @"POST"; 
 // 2>       
 requestM.HTTPBody = dataM; 
 // 3>   Content-Type 
 NSString *typeStr = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", randomIDStr]; 
 [requestM setValue:typeStr forHTTPHeaderField:@"Content-Type"]; 
 // 4>        
 NSString *lengthStr = [NSString stringWithFormat:@"%@", @([dataM length])]; 
 [requestM setValue:lengthStr forHTTPHeaderField:@"Content-Length"]; 
 
 return [requestM copy]; 
} 
2.PUT 방식 으로 업로드
session 의 upload 방법 은 PUT 업로드 에 만 사용 할 수 있 고 POST 업로드 에 사용 할 수 없습니다.
PUT 방식 으로 업로드 하 는 장점:(인증 필요)
*POST 처럼 문자열 을 맞 추 지 않 아 도 됩 니 다.
*base 64 로 인증 을 직접 인 코딩 합 니 다.session 의 upload 를 호출 하면 됩 니 다.
*파일 크기 제한 이 없습니다.
*인 스 턴 트 메 신 저 에 많이 쓰 인 다.(사진 보 내기/음성 보 내기)
- (void)putFile 
{ 
 // 1. url              
 NSURL *url = [NSURL URLWithString:@"http://localhost/uploads/abcd"]; //abcd     
 
 // 2. request 
 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; 
 request.HTTPMethod = @"PUT"; 
// request.HTTPMethod = @"DELETE"; 
 
 //        
 // BASE64  :                   “          ”,                 ! 
 //              
 // BASE64     ,           
 NSString *authStr = @"admin:123"; 
 NSString *authBase64 = [NSString stringWithFormat:@"Basic %@", [self base64Encode:authStr]]; 
 [request setValue:authBase64 forHTTPHeaderField:@"Authorization"]; 
 
 // 3. URLSession 
 NSURLSession *session = [NSURLSession sharedSession]; 
 
 // 4.  session     
 NSURL *localURL = [[NSBundle mainBundle] URLForResource:@"001.png" withExtension:nil]; 
 [[session uploadTaskWithRequest:request fromFile:localURL completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { 
  
 NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; 
  
 NSLog(@"sesult---> %@ %@", result, [NSThread currentThread]); 
 }] resume]; 
} 
 
- (NSString *)base64Encode:(NSString *)str 
{ 
 // 1.              
 NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding]; 
 
 // 2.         base64   
 NSString *result = [data base64EncodedStringWithOptions:0]; 
 
 NSLog(@"base464--> %@", result); 
 
 return result; 
} TIPS:session 사용 주의
*네트워크 세 션 으로 프로그래머 가 네트워크 서 비 스 를 편리 하 게 사용 할 수 있 습 니 다.
*예:현재 업로드 한 파일 의 진 도 를 얻 을 수 있 습 니 다.
*NSURLSession 의 작업 은 기본적으로 비동기 입 니 다.(다른 스 레 드 에서 작업)
*Task 는 세 션 에서 시 작 됩 니 다.
*네트워크 요청 은 모두 오류 처 리 를 해 야 합 니 다.
*session 은 기본적으로 걸 려 있 습 니 다.resume 이 있어 야 시작 할 수 있 습 니 다.
이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
View의 레이아웃 방법을 AutoLayout에서 따뜻한 손 계산으로 하면 성능이 9.26배로 된 이야기이 기사는 의 15 일째 기사입니다. 어제는 에서 이었습니다. 손 계산을 권하는 의도는 없고, 특수한 상황하에서 계측한 내용입니다 화면 높이의 10 배 정도의 contentView가있는 UIScrollView 레이아...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.