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];

参考资料

Multipart/form-data POST文件上传详解
iOS网络请求之multipart/form-data提交数据
iOS里实现multipart/form-data格式上传文件

猜你喜欢

转载自blog.csdn.net/kaiyuanheshang/article/details/60503190