iOS 原生api上传图片

#define SPEncode(str) [str dataUsingEncoding:NSUTF8StringEncoding]

-(void)uploadHeadImage:(UIImage *)image andWithPicker:(UIImagePickerController *)picker{

    //记录image的类型和data

    NSData *imageData;

    NSString *imageFormat;

    if (UIImagePNGRepresentation(image) == nil) {

        imageFormat = @"Content-Type: image/jpeg \r\n";

        imageData = UIImageJPEGRepresentation(image, 1.0);

        return;

    }else{

//        imageFormat = @"Content-Type: image/png \r\n";

//        imageData = UIImagePNGRepresentation(image,0.1);

        imageFormat = @"Content-Type: image/jpeg \r\n";

        imageData = UIImageJPEGRepresentation(image, 0.1);

    }

    //请求地址

    NSString *userIdStr = [[NSUserDefaults standardUserDefaults] stringForKey:@"myUserId"];

    NSString *urlStr = [NSString stringWithFormat:@"%@/api/upload",[[NSUserDefaults standardUserDefaults] objectForKey:@"myBaseUrl"]];

    NSURL *requestUrl = [NSURL URLWithString:urlStr];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:requestUrl];

    request.HTTPMethod = @"POST";


    //设置请求体

    NSMutableData *body = [NSMutableData data];


    /**请求参数**/

    [body appendData:SPEncode(@"--SPSWL\r\n")];

    NSString *disposition = @"Content-Disposition: form-data; name=\"file\";filename=\"001.png\"\r\n";

    [body appendData:SPEncode(disposition)];

    [body appendData:SPEncode(imageFormat)];


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

    [body appendData:imageData];

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

    /**普通参数**/

    [body appendData:SPEncode(@"--SPSWL\r\n")];

    NSString *dispositions = @"Content-Disposition: form-data; name=\"userId\"\r\n";

    [body appendData:SPEncode(dispositions)];

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

    [body appendData:SPEncode(userIdStr)];

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

    /**参数结束**/

    [body appendData:SPEncode(@"--SPSWL--\r\n")];

    request.HTTPBody = body;

    //设置请求体的长度

    NSInteger length = [body length];

    [request setValue:[NSString stringWithFormat:@"%ld",length] forHTTPHeaderField:@"Content-Length"];


    //设置post请求文件上传

    [request setValue:@"multipart/form-data;boundary=SPSWL" forHTTPHeaderField:@"Content-Type"];

    [NSURLConnection sendAsynchronousRequest:request

                                      queue:[NSOperationQueue mainQueue]

                          completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {


                              NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];

                              if(dict){

                                  if([dict[@"code"] integerValue] == 0){


                                      [picker dismissViewControllerAnimated:YES completion:nil];


                                      NSDictionary *dict1 = @{@"type":@"changeHeadImage",@"imageUrl":dict[@"url"]};

                                      NSString *jsonStr = [self convertToJsonData:dict1];

                                      std::string jsStr = *new std::string([jsonStr UTF8String]);

                                      Global::callJS(jsStr);

                                  }else{

                                      NSLog(@"errMsg:%@",dict[@"msg"]);

                                  }

                              }

                          }];

}

你可能感兴趣的:(iOS 原生api上传图片)