本文将带你了解IOS开发入门iOS里实现multipart/form-data格式上传文件,希望本文对大家学IOS有所帮助。
iOS里实现multipart/form-data格式上传文件。
Http 请求(后面统一称为报文),包含请求头和请求体两部分,格式如下:
?123456789POST /
HTTP/1.1Content-Type:application/x-www-form-urlencodedAccept-Encoding: gzip,
deflateHost: w.sohu.comContent-Length: 21Connection: Keep-AliveCache-Control:
no-cache txt1=hello&txt2=world
Objective-C 代码如下:
?123456789101112131415161718192021222324252627// #define
kHttpRequestHeadContentTypeValueMultipart @"multipart/form-data;
boundary=forjoritest"// #define kHttpRequestHeadContentTypeKey
@"Content-Type"// #define kHttpRequestHeadBoundaryValue
@"forjoritest"// #define kHttpRequestContentDisposition
@"Content-Disposition: form-data"NSURLSessionConfiguration
*configuration = [NSURLSessionConfiguration
defaultSessionConfiguration];NSURLSession *session = [NSURLSession
sessionWithConfiguration:configuration]; NSURL *url = [NSURL
URLWithString:[kDetectUrl
stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];NSMutableURLRequest
*mutableRequest = [NSMutableURLRequest
requestWithURL:url];mutableRequest.HTTPMethod =
@"POST";[mutableRequest
addValue:kHttpRequestHeadContentTypeValueMultipart
forHTTPHeaderField:kHttpRequestHeadContentTypeKey]; NSString *body =
[NSString stringWithFormat:@"--%@\r\n%@;name=\"%@\"\r\n\r\n%@",
kHttpRequestHeadBoundaryValue, kHttpRequestContentDisposition,
kUploadParamApiKey, @"ApiKey"];body = [body
stringByAppendingString:[NSString stringWithFormat:@"\r\n--%@\r\n%@;
name=\"%@\"\r\n\r\nApiSecret", kHttpRequestHeadBoundaryValue,
kHttpRequestContentDisposition, kUploadParamApiSecret]];body = [body
stringByAppendingString:[NSString stringWithFormat:@"\r\n--%@\r\n%@;
name=\"%@\"\r\n\r\n1", kHttpRequestHeadBoundaryValue,
kHttpRequestContentDisposition, @"return_landmark"]];body = [body
stringByAppendingString:[NSString stringWithFormat:@"\r\n--%@\r\n%@;
name=\"%@\"\r\n\r\ngender,age", kHttpRequestHeadBoundaryValue,
kHttpRequestContentDisposition, @"return_attributes"]];body = [body
stringByAppendingString:[NSString stringWithFormat:@"\r\n--%@\r\n%@;
name=\"%@\"; filename=\"%@\"
Content-Type=image/jpeg\r\n\r\n", kHttpRequestHeadBoundaryValue,
kHttpRequestContentDisposition, kUploadParamImageFile,
kUploadParamImageFile]]; NSMutableData *data = [NSMutableData
data];[data appendData:[body dataUsingEncoding:NSUTF8StringEncoding]];[data
appendData:image];[data appendData:[[NSString
stringWithFormat:@"\r\n--%@--\r\n", kHttpRequestHeadBoundaryValue]
dataUsingEncoding:NSUTF8StringEncoding]];mutableRequest.HTTPBody =
data;[mutableRequest setValue:[NSString stringWithFormat:@"%lu",
(unsigned long)data.length]
forHTTPHeaderField:@"Content-Length"];NSURLSessionUploadTask *task
= [session uploadTaskWithRequest:mutableRequest fromData:nil
completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable
response, NSError * _Nullable error) { }];[task
resume];
本文由职坐标整理并发布,希望对同学们有所帮助。了解更多详情请关注职坐标移动开发之IOS频道!