(1)方式一
// static NSString *boundry = @"----------V2ymHFg03ehbqgZCaKO6jy";//设置边界
-(void)uploadDataWithURL:(NSString *)url postData:(NSDictionary*)postData image:(UIImage *)image {
NSURL *reqUrl = [NSURL URLWithString:url];
NSMutableURLRequest *urlRequest = [[NSMutableURLRequest alloc] initWithURL:reqUrl cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30];
urlRequest.HTTPMethod = @"POST";
//设置请求头 在请求头中添加content-type字段
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; charset=utf-8;boundary=%@",boundry];
[urlRequest setValue:contentType forHTTPHeaderField:@"Content-Type"];
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
//NSURLSession
NSURLSession *session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:[[NSOperationQueue alloc]init]];
//定义上传操作
NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:urlRequest fromData:[self getBodydataWithImage:[UIImage imageNamed:@"chat_send_nor"]] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSLog(@"响应结果:%@", response);
NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"返回数据:\n%@",str);
}];
[uploadTask resume];
}
- (NSData *)getBodydataWithImage:(UIImage *)image{
NSData *fileData = UIImageJPEGRepresentation(image, 0.8);
NSString *fileName=@"image";
NSMutableString *bodyString = [[NSMutableString alloc] init];
[bodyString appendFormat:@"--%@\r\n",boundry];
[bodyString appendFormat:@"Content-Disposition: form-data; name=\"FileName\"\r\n"];
[bodyString appendFormat:@"Content-Type: text/plain; charset=\"utf-8\"\r\n\r\n"];
[bodyString appendFormat:@"aaa%@.jpg\r\n",fileName];
//PostID
// [bodyString appendFormat:@"--%@\r\n",boundry];
// [bodyString appendFormat:@"Content-Disposition: form-data; name=\"PostID\"\r\n"];
// [bodyString appendFormat:@"Content-Type: text/plain; charset=\"utf-8\"\r\n\r\n"];
// [bodyString appendFormat:@"%@\r\n",self.uuID];
//pic
[bodyString appendFormat:@"--%@\r\n",boundry];
[bodyString appendFormat:@"Content-Disposition: form-data; name=\"file\"; filename=\"%@.jpg\"\r\n",fileName];
[bodyString appendFormat:@"Content-Type: image/jpeg\r\n\r\n"];
//[bodyString appendFormat:@"Content-Type: application/octet-stream\r\n\r\n"];
//string --> data
NSMutableData *bodyData = [NSMutableData data];
//前面的bodyString, 其他参数
[bodyData appendData:[bodyString dataUsingEncoding:NSUTF8StringEncoding]];
//图片数据
[bodyData appendData:fileData];
//结束的分隔线
NSString *endStr = [NSString stringWithFormat:@"\r\n--%@--\r\n",boundry];
//拼接到bodyData最后面
[bodyData appendData:[endStr dataUsingEncoding:NSUTF8StringEncoding]];
return bodyData;
}
(2)方式二
-(void)uploadDataWithURL:(NSString *)url image:(UIImage *)image{
NSData *data;
UIImage *image1 = [UIImage imageNamed:@"chat_send_nor"];
if ((data = UIImageJPEGRepresentation(image1, 1)) == nil){
data = UIImagePNGRepresentation(image1);
} else {
//图片压缩方式1
/*
CGFloat compression = 0.9f;
CGFloat maxCompression = 0.1f;
data = UIImageJPEGRepresentation(image1, compression);
while ([data length] > 1*100*1024 && compression > maxCompression) {
compression -= 0.1;
data = UIImageJPEGRepresentation(image1, compression);
}
*/
//图片压缩方式2
NSInteger maxLength = 100 * 1024;
CGFloat compression = 1;
data = UIImageJPEGRepresentation(image1, compression);
if (data.length > maxLength) {
CGFloat max = 1;
CGFloat min = 0;
for (int i = 0; i < 6; ++i) {
compression = (max + min) / 2;
data = UIImageJPEGRepresentation(image1, compression);
if (data.length < maxLength * 0.9) {
min = compression;
} else if (data.length > maxLength) {
max = compression;
} else {
break;
}
}
}
}
NSString *boundary = [NSString stringWithFormat:@"Boundary+%08X%08X", arc4random(), arc4random()];
NSMutableString *topStr = [NSMutableString string];
[topStr appendFormat:@"--%@\r\n",boundary];
// [topStr appendFormat:@"Content-Disposition: form-data; name=\"FileName\"\r\n"];
// [topStr appendFormat:@"Content-Type: text/plain; charset=\"utf-8\"\r\n\r\n"];
// [topStr appendFormat:@"%@.jpg\r\n",@"image"];
// [topStr appendFormat:@"--%@\r\n",boundary];
[topStr appendFormat:@"Content-Disposition: form-data; name=\"file\"; filename=\"%@.jpg\"\r\n",@"image"];
[topStr appendFormat:@"Content-Type: image/jpeg\r\n\r\n"];
NSMutableData *body = [NSMutableData data];
[body appendData:[topStr dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:data];
NSString *endStr = [NSString stringWithFormat:@"\r\n--%@--\r\n",boundary];
[body appendData:[endStr dataUsingEncoding:NSUTF8StringEncoding]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:30];
request.HTTPMethod = @"POST";
request.HTTPBody = body;
[request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)body.length] forHTTPHeaderField:@"Content-Length"];
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; charset=utf-8;boundary=%@",boundary];
[request setValue:contentType forHTTPHeaderField:@"Content-Type"];
NSURLSessionDataTask *task = [[NSURLSession sharedSession]dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
dispatch_async(dispatch_get_main_queue(), ^{
if (error) {
NSLog(@"[error localizedDescription] == %@",[error localizedDescription]);
}else{
NSLog(@" 图片上传 响应结果:%@", response);
id rdic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
NSLog(@"图片上传 返回数据:\n%@",rdic);
}
});
}];
[task resume];
}
请求头(图片来自Charles 4.5.6)
·