iOS裡實現multipart/form-data格式上傳文件。
Http 請求(後面統一稱為報文),包含請求頭和請求體兩部分,格式如下:
POST / HTTP/1.1 Content-Type:application/x-www-form-urlencoded Accept-Encoding: gzip, deflate Host: w.sohu.com Content-Length: 21 Connection: Keep-Alive Cache-Control: no-cache txt1=hello&txt2=world
Objective-C 代碼如下:
// #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];