1、 先看下表单页面的HTML代码
<form name="form1" id="form1" enctype="multipart/form-data" method="post" action="/ashx/uploadPic.ashx" >
<input id="Hidden1" type="hidden" name="UploadData"
value="{'key1':'value1'}" />
<p>
第一张图片:<input type="file" name="photoF" id="photo">
</p>
<p>
第二张图片:<input type="file" name="photoS" id="photo">
</p>
<p>
<input type="submit" name="b1" value="提交">
</p>
</form>
2、 看完form表单的内容接下来我们来写客户端的提交代码
从上面的表单可以看出需要提交的内容有:json字符串和两张照片
//需要提交的数据
NSData *data_f = UIImageJPEGRepresentation(zImage, 0.8);
NSData *data_s = UIImageJPEGRepresentation(fImage, 0.8);
NSDictionary * dic = [NSMutableDictionary new];
[dic setValue:@"value1" forKey:@"key1"];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:nil];
//配置AF
AFHTTPSessionManager *manage = [AFHTTPSessionManager manager];
[manage.requestSerializer setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
manage.requestSerializer = [AFHTTPRequestSerializer serializer];
manage.responseSerializer = [AFHTTPResponseSerializer serializer];
manage.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html", @"text/json", @"text/javascript",@"text/plain", nil];
[manage POST:@"提交的URL" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
//当提交一张图片或一个文件的时候 name 可以随便设置,服务端直接能拿到,如果服务端需要根据name去取不同文件的时候,则appendPartWithFileData 方法中的 name 需要根据form的中的name一一对应
[formData appendPartWithFormData:jsonData name:@"UploadData"];
[formData appendPartWithFileData: data_f name:@"photoF" fileName:@"a.jpg" mimeType:@"image/jpeg"];
[formData appendPartWithFileData: data_s name:@"photoS" fileName:@"b.jpg" mimeType:@"image/jpeg"];
} progress:^(NSProgress * _Nonnull uploadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSDictionary *responseDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
}];
网友评论