由于服务器要求以文件流上传头像至服务器,之前使用的是ASIFormDataRequest,只需简单设置,就可以实现上传
[request setFile:imageDirectory forKey:@"xxxx"];
但是由于公司要求不得使用第三方库。所以只能自己写,找了好多地方终于找到一篇文章
通过简单的更改就可以实现上传。代码如下:
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
//分界线的标识符
NSString *formBoundary = @"14141571a1471414541s1a";
//声明requestData,用来放入http body
NSMutableData *requestData=[NSMutableData data];
//分界线 --14141571a1471414541s1a
NSString *startBoundary=[[NSString alloc]initWithFormat:@"--%@",formBoundary];
//结束符 14141571a1471414541s1a--
NSString *endMPboundary=[[NSString alloc]initWithFormat:@"%@--",startBoundary];
UIImage *image = [UIImage imageWithContentsOfFile:imageDirectory];
//添加image并转成二进制
NSData* data = UIImagePNGRepresentation(image);
//http body的字符串
NSMutableString *body=[[NSMutableString alloc]init];
if (image) {
添加分界线,换行
[body appendFormat:@"%@\r\n",startBoundary];
//※※※※※※重要:::声明pic字段,文件名为"icon",path为图片路径
[body appendFormat:@"Content-Disposition: form-data; path=\"%@\"; filename=\"icon\"\r\n",imageDirectory];
//声明上传文件的格式
[body appendFormat:@"Content-Type: image/png\r\n\r\n"];
}
//声明结束符:--14141571a1471414541s1a--
NSString *end=[[NSString alloc]initWithFormat:@"\r\n%@",endMPboundary];
//将body字符串转化为UTF8格式的二进制
[requestData appendData:[body dataUsingEncoding:NSUTF8StringEncoding]];
//不要忘记将image的data加入
[requestData appendData:data];
//加入结束符--14141571a1471414541s1a--
[requestData appendData:[end dataUsingEncoding:NSUTF8StringEncoding]];
//设置HTTPHeader中Content-Type的等值
NSString *content=[[NSString alloc]initWithFormat:@"multipart/form-data; boundary=%@",formBoundary];
[request setValue:content forHTTPHeaderField:@"Content-Type"];
// 实测没有Content-Length,也可以,因为长度是服务器控制的。
// [request setValue:[NSString stringWithFormat:@"%d", [requestData length]] forHTTPHeaderField:@"Content-Length"];
[request setURL:[NSURL URLWithString:strUrl]];
[request setHTTPMethod:@"POST"];
[request setValue:token forHTTPHeaderField:@"token"];
[request setHTTPBody:requestData];
经测试,一切OK。