NSString *fNameValue = [[filePath pathComponents]lastObject];
NSString *nameValue = [fNameValue stringByDeletingPathExtension];
将传入的文件变为二进制:
NSData *imageData = [NSDatadataWithContentsOfFile:filePath];
组织http request body 的内容:
NSString *stringBoundary = @"----WebKitFormBoundarygTijO0scBddIKz8T";//body
不同边界的标识
NSMutableData *postBody = [[NSMutableData alloc] init];
[postBody appendData:[[NSString stringWithFormat:@"\r\n\r\n--%@\r\n",
stringBoundary]dataUsingEncoding:NSUTF8StringEncoding]];
// 设置开始标识
[postBody appendData:[[NSString stringWithFormat:@"Content-Disposition:
form-data; name="file";
filename="%@"\r\n",fNameValue]dataUsingEncoding:NSUTF8StringEncoding]];
//相当于web表单的file域
NSString *contentFileType =[NSStringstringWithFormat:@"Content-Type:
%@\r\n\r\n",fileType];
[postBody appendData:[contentFileTypedataUsingEncoding:NSUTF8StringEncoding]][postBody appendData:imageData];
NSString *hhh_date =[NSString stringWithFormat:@"\r\n--%@\r\n",
stringBoundary]; //第二段标识
[postBody appendData:[hhh_datedataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[@"Content-Disposition:
form-data;
name="timestamp"\r\n\r\n"dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[@"0.38387341564521194"dataUsingEncoding:NSUTF8StringEncoding]];
//设置表单的其他参数
NSArray *array =[parame allKeys];
for (NSString *key in array)
{
[postBody appendData:[hhh_datedataUsingEncoding:NSUTF8StringEncoding]];
NSString *ContentDisposition
=[NSStringstringWithFormat:@"Content-Disposition:
form-data;
name="%@"\r\n\r\n",key];
[postBody appendData:[ContentDispositiondataUsingEncoding:NSUTF8StringEncoding]];
NSString *valueStr = [NSStringstringWithFormat:@"%@",[parame objectForKey:key]];
[postBody appendData:[valueStrdataUsingEncoding:NSUTF8StringEncoding]];
}
[postBody appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",
stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
----end body 数据准备完毕
发起POST 请求:
AFAppDotNetAPIClient *httpClient = [AFAppDotNetAPIClient sharedClient];
NSURLSessionDataTask *task = [httpClient POST:url parameters:nil
constructingBodyWithBlock:^(id<<span
style="color: #3c828c">AFMultipartFormData> formData) {
[formData appendPartWithFileData:postBody name:nameValue fileName:fNameValue
mimeType:fileType];
} success:^(NSURLSessionDataTask *task, id responseObject)
{
if (completBlock) {
completBlock(responseObject,nil);
}
} failure:^(NSURLSessionDataTask *task, NSError *error)
{
if (completBlock) {
completBlock(nil,error);
}
}];
return task;