ios文件,图片上传服务器

时间:2022-09-05 12:17:37

- (void)upload:(NSString *)name filename:(NSString *)filename mimeType:(NSString *)mimeType data:(NSData *)data parmas:(NSDictionary *)params
{
// 文件上传
NSURL *url = [NSURLURLWithString:@"http://123.57.89.97:7070/t2o/app/member/modifyFace"];
NSMutableURLRequest *request = [NSMutableURLRequestrequestWithURL:url];
request.HTTPMethod =@"POST";

// 设置请求体
NSMutableData *body = [NSMutableDatadata];

/***************文件参数***************/
// 参数开始的标志
[body appendData:YYEncode(@"--YY\r\n")];
// name : 指定参数名(必须跟服务器端保持一致)
// filename : 文件名
NSString *disposition = [NSStringstringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\n", name, filename];
[body appendData:YYEncode(disposition)];
NSString *type = [NSStringstringWithFormat:@"Content-Type: %@\r\n", mimeType];
[body appendData:YYEncode(type)];

[body appendData:YYEncode(@"\r\n")];
[body appendData:data];
[body appendData:YYEncode(@"\r\n")];

/***************普通参数***************/
[params enumerateKeysAndObjectsUsingBlock:^(id key,id obj, BOOL *stop) {
// 参数开始的标志
[body appendData:YYEncode(@"--YY\r\n")];
NSString *disposition = [NSStringstringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n", key];
[body appendData:YYEncode(disposition)];

[body appendData:YYEncode(@"\r\n")];
[body appendData:YYEncode(obj)];
[body appendData:YYEncode(@"\r\n")];
}];

/***************参数结束***************/
// YY--\r\n
[body appendData:YYEncode(@"--YY--\r\n")];
request.HTTPBody = body;

// 设置请求头
// 请求体的长度
[request setValue:[NSStringstringWithFormat:@"%zd", body.length]forHTTPHeaderField:@"Content-Length"];
// 声明这个POST请求是个文件上传
[request setValue:@"multipart/form-data; boundary=YY"forHTTPHeaderField:@"Content-Type"];

// 发送请求
[NSURLConnectionsendAsynchronousRequest:request queue:[NSOperationQueuemainQueue] completionHandler:^(NSURLResponse *response,NSData *data, NSError *connectionError) {
if (data) {
NSDictionary *dict = [NSJSONSerializationJSONObjectWithData:data options:NSJSONReadingMutableLeaveserror:nil];
NSLog(@"上传成功========%@", dict);
} else {
NSLog(@"上传失败");
}
}];
}

NSDictionary * dic = [NSDictionarydictionaryWithObjectsAndKeys:myDelegate.MEMBER_ID,@"MEMBER_ID",nil];
[selfupload:@"face"filename:@"picker.png"mimeType:@"image/png"data:data parmas:dic];

self upload:<#(NSString *)#> filename:<#(NSString *)#> mimeType:<#(NSString *)#> data:<#(NSData *)#> parmas:<#(NSDictionary *)#>


 图片参数  -  图片名  - 类型 -- 本地图片路径 - - 其它参数



1、在iOS开发中,图片上传的请求体非常难写,格式要求非常严格,出一点错误都会造成上传失败,或请求数据失败,先看格式:

--Boundary+72D4CD655314C423
Content-Disposition: form-data; name="uploadFile"; filename="001.png"
Content-Type:image/png
Content-Transfer-Encoding: binary

... contents of boris.png ...
--Boundary+72D4CD655314C423--
这是一个不带其他任务参数,body中只有一张图就要写成这样
分别说明一下:
--Boundary+72D4CD655314C423   // 分割符,以“--”开头,后面的字随便写,只要不写中文即可
Content-Disposition: form-data; name="uploadFile"; filename="001.png"  // 这里注明服务器接收图片的参数(类似于接收用户名的userName)及服务器上保存图片的文件名
Content-Type:image/png  // 图片类型为png
Content-Transfer-Encoding: binary  // 编码方式
  // 这里是空一行,必不可少!!
... contents of boris.png ...  // 图片数据部分
--Boundary+72D4CD655314C423--  // 分隔符后面以"--"结尾,表明结束

2、如果有其他表单数据,如传用户ID等参数,也要写成以上格式:
--Boundary+72D4CD655314C423
Content-Disposition: form-data; name="userId"
     
254
--Boundary+72D4CD655314C423
Content-Disposition: form-data; name="shopId"
     
18718



-
(
void )upload
{
     NSString *urlStr = @"http://localhost/upload.php" ;
     NSMutableURLRequest *request = [ NSMutableURLRequest requestWithURL:[ NSURL URLWithString:urlStr] cachePolicy:0 timeoutInterval:5.0f];
     
     [ self setRequest:request];
     
     NSLog ( @"开始上传..." );
     [ NSURLConnection sendAsynchronousRequest:request queue:[[ NSOperationQueue alloc] init] completionHandler:^( NSURLResponse *response, NSData *data, NSError *connectionError) {
         
         NSLog ( @"Result--%@" , [[ NSString alloc] initWithData:data encoding: NSUTF8StringEncoding ]);
         
     }];
}
 
-
(
void )setRequest:( NSMutableURLRequest *)request
{
     NSString *boundary = [ NSString stringWithFormat: @"Boundary+%08X%08X" , arc4random(), arc4random()];
     NSMutableData *body = [ NSMutableData data];
     
     // 表单数据
     NSMutableDictionary *param = [[ NSMutableDictionary alloc] init];
     [param setValue: @"254" forKey: @"empId" ];
     [param setValue: @"18718" forKey: @"shopId" ];
     
     /** 遍历字典将字典中的键值对转换成请求格式:
      --Boundary+72D4CD655314C423
      Content-Disposition: form-data; name="empId"
      
      254
      --Boundary+72D4CD655314C423
      Content-Disposition: form-data; name="shopId"
      
      18718
      */
     [param enumerateKeysAndObjectsUsingBlock:^( id key, id obj, BOOL *stop) {
         NSMutableString *fieldStr = [ NSMutableString string];
         [fieldStr appendString:[ NSString stringWithFormat: @"--%@\r\n" , boundary]];
         [fieldStr appendString:[ NSString stringWithFormat: @"Content-Disposition: form-data; name=\"%@\"\r\n\r\n" , key]];
         [fieldStr appendString:[ NSString stringWithFormat: @"%@" , obj]];
         [body appendData:[fieldStr dataUsingEncoding: NSUTF8StringEncoding ]];
         [body appendData:[ @"\r\n" dataUsingEncoding: NSUTF8StringEncoding ]];
     }];
     
     
     /// 图片数据部分
     NSMutableString *topStr = [ NSMutableString string];
     NSString *path = [[ NSBundle mainBundle] pathForResource: @"001.jpg" ofType: nil ];
     NSData *data = [ NSData dataWithContentsOfFile:path];
     
     /**拼装成格式:
      --Boundary+72D4CD655314C423
      Content-Disposition: form-data; name="uploadFile"; filename="001.png"
      Content-Type:image/png
      Content-Transfer-Encoding: binary
      
      ... contents of boris.png ...
      */
     [topStr appendString:[ NSString stringWithFormat: @"--%@\r\n" , boundary]];
     [topStr appendString: @"Content-Disposition: form-data; name=\"uploadFile\"; filename=\"001.png\"\r\n" ];
     [topStr appendString: @"Content-Type:image/png\r\n" ];
     [topStr appendString: @"Content-Transfer-Encoding: binary\r\n\r\n" ];
     [body appendData:[topStr dataUsingEncoding: NSUTF8StringEncoding ]];
     [body appendData:data];
     [body appendData:[ @"\r\n" dataUsingEncoding: NSUTF8StringEncoding ]];
     
     // 结束部分
     NSString *bottomStr = [ NSString stringWithFormat: @"--%@--" , boundary];
     /**拼装成格式:
      --Boundary+72D4CD655314C423--
      */
     [body appendData:[bottomStr dataUsingEncoding: NSUTF8StringEncoding ]];
     
     // 设置请求类型为post请求
     request.HTTPMethod = @"post" ;
     // 设置request的请求体
     request.HTTPBody = body;
     // 设置头部数据,标明上传数据总大小,用于服务器接收校验
     [request setValue:[ NSString stringWithFormat: @"%d" , body.length] forHTTPHeaderField: @"Content-Length" ];
     // 设置头部数据,指定了http post请求的编码方式为multipart/form-data(上传文件必须用这个)。
     [request setValue:[ NSString stringWithFormat: @"multipart/form-data; boundary=%@" ,boundary] forHTTPHeaderField: @"Content-Type" ];
}