一.创建文件
二.在.m文件中添加
//URL上传接口 fileName图片名称 data图片的数据流
+(instancetype)requestWithURL:(NSURL *)URL fileName:(NSString *)fileName localImageData:(NSData *)data
{
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL cachePolicy:1 timeoutInterval:2.0f];
request.HTTPMethod = @"POST";
request.timeoutInterval = 1000.0; //请求超时
// 拼接请求体
NSMutableData *requestData = [NSMutableData data];
// 1.分隔符
NSString *boundary = @"72D4CD655314C423";
NSMutableString *imageString = [NSMutableString stringWithFormat:@"\r\n--%@\r\n",boundary];
// 2.Content-Disposition: form-data; name="uploadFile"; filename="001.png"\r\n // 这里注明服务器接收图片的参数(类似于接收用户名的userName)及服务器上保存图片的文件名
[imageString appendString:[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"uploadFile\"; filename=\"%@\"\r\n",fileName]];
// 3.Content-Type:image/png \r\n // 图片类型为png
[imageString appendString:[NSString stringWithFormat:@"Content-Type:application/octet-stream\r\n"]];
// 4.Content-Transfer-Encoding: binary\r\n\r\n // 编码方式
[imageString appendString:@"Content-Transfer-Encoding: binary\r\n\r\n"];
// 转成二进制
[requestData appendData:[imageString dataUsingEncoding:NSUTF8StringEncoding]];
// 5.文件数据部分 --data为图片的数据流
[requestData appendData:data];
// 6.分隔符结尾
[requestData appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary]dataUsingEncoding:NSUTF8StringEncoding]];
// 请求体
request.HTTPBody = requestData;
// 设置请求头
// Content-Type
NSString *headStr=[NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
[request setValue:headStr forHTTPHeaderField:@"Content-Type"];
return request;
}
三.ViewController内的调用
1.相册中选中图片获取数据
// 当得到照片或者视频后,调用该方法
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
// 判断获取类型:图片
UIImage *theImage = nil;
// 判断,图片是否允许修改
if ([picker allowsEditing]){
//获取用户编辑之后的图像
theImage = [info objectForKey:UIImagePickerControllerEditedImage];
} else {
// 照片的元数据参数
theImage = [info objectForKey:UIImagePickerControllerOriginalImage];
}
//数据流
self.imageDataSec=UIImageJPEGRepresentation(theImage, 0.1);
[self upDataImage];
[picker dismissViewControllerAnimated:YES completion:^{
}];
}
-(void)upDataImage{
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url fileName:[NSString stringWithFormat:@"%@.jpg",imgName] localFilepath:self.imageDataSec];
//连接(NSURLSession)
NSURLSession *session=[NSURLSession sharedSession];
NSURLSessionDataTask *dataTask=[session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
id result=[NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(@"%@",result);
}];
[dataTask resume];
}
网友评论