iOS oc multipart/form-data上传文件请求
时间: 2023-11-18 09:04:09 浏览: 53
以下是iOS Objective-C实现multipart/form-data格式上传文件的示例代码:
```objective-c
// 设置请求URL
NSURL *url = [NSURL URLWithString:@"http://example.com/upload"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
// 设置请求方法为POST
[request setHTTPMethod:@"POST"];
// 设置请求头
NSString *boundary = @"Boundary+0xAbCdEfGbOuNdArY";
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
[request setValue:contentType forHTTPHeaderField:@"Content-Type"];
// 设置请求体
NSMutableData *body = [NSMutableData data];
// 添加文件数据
NSData *fileData = UIImageJPEGRepresentation(image, 1.0);
if (fileData) {
[body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"file\"; filename=\"%@\"\r\n", @"image.jpg"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Type: %@\r\n\r\n", @"image/jpeg"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:fileData];
[body appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
}
// 添加其他参数
NSDictionary *parameters = @{@"key1": @"value1", @"key2": @"value2"};
for (NSString *key in parameters) {
[body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", key] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"%@\r\n", parameters[key]] dataUsingEncoding:NSUTF8StringEncoding]];
}
// 添加请求结束标志
[body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// 设置请求体长度
[request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)[body length]] forHTTPHeaderField:@"Content-Length"];
// 设置请求体
[request setHTTPBody:body];
// 发送请求
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
// 处理响应
}];
[task resume];
```