iOS 업로드 파일 formdata

2494 단어
직접 부호

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];

    [request setURL:[NSURLURLWithString:aUrl]];

    [request setHTTPMethod:@"POST"];



    NSString *boundary = @"---------------------------14737809831466499882746641449";

    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];

    [request addValue:contentTypeforHTTPHeaderField:@"Content-Type"];

    [request addValue:@"token" forHTTPHeaderField:@"Auth-Token"];

    NSMutableData *body = [NSMutableData data];

 [body appendData:[[NSString stringWithFormat:@"--%@\r
", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"key\""]dataUsingEncoding:NSUTF8StringEncoding]]; // \r
\r
, name [body appendData:[@"\r
\r
" dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[[NSString stringWithFormat:@"value"]dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[@"\r
" dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[[NSString stringWithFormat:@"--%@\r
", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"file\"; filename=\"uploadfile\"\r
"] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[@"Content-Type: application/octet-stream\r
\r
" dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[NSDatadataWithData:upLoadParam.data]]; [body appendData:[@"\r
" dataUsingEncoding:NSUTF8StringEncoding]]; // close form [body appendData:[[NSString stringWithFormat:@"--%@--\r
", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; // setting the body of the post to the request [request setHTTPBody:body]; NSURLSession *session = [NSURLSession sharedSession]; NSURLSessionDataTask*task = [sessiondataTaskWithRequest:requestcompletionHandler:^(NSData*_Nullabledata,NSURLResponse*_Nullableresponse,NSError*_Nullableerror) { if(error ==nil) { NSLog(@"response:%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]); } else } }]; [task resume];

좋은 웹페이지 즐겨찾기