iOS大咖说程序员

iOS 上传图片(base64 和 file类型)

2018-04-18  本文已影响66人  苦可乐

1. base64 上传图片


 *  上传图片到服务器

 *

 *  @param image

 *  @param photoID

 *  @param photoType

 */

- (void)uploadPhotoToSrver:(UIImage *) image withPhotoID:(NSString *)photoID andPhotoType:(PhotoType)type andImageText:(NSString *)text {

    static int upLoadCount = 0;

    NSData *imageData = UIImageJPEGRepresentation(scaledImg, 0.6); 

    NSString *dataStr = [imageData base64EncodedStringWithOptions:0];

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/xml"];

    manager.requestSerializer = [AFHTTPRequestSerializer serializer];

    manager.responseSerializer = [AFHTTPResponseSerializer serializer];

//参数

    NSDictionary *parameters = @{@"UserID" : userInfo.UserID,  @"imageDataStr": dataStr};

// url String

    NSString *baseURL = [NSString stringWithFormat: @"%@%@", WEBBASEURL, WEBUploadPhotoDataAction];



    [manager POST:baseURL parameters:parameters success:^(AFHTTPRequestOperation *operation,id responseObject) {

        NSLog(@"上传成功");

    }failure:^(AFHTTPRequestOperation *operation,NSError *error) {

        MYNSLOG(@"~~~~~~~~%@",error);

    }];

    

}

2. file 文件上传图片 (对应服务器上的[file]类型)


- (void)personalUploadHeadImgInterfaceWithImage:(UIImage *)uploadImage  {

// 参数

    NSDictionary *parameterDict = @{@"userkey" : appDelegate.userKeyString};

    

    //网络请求管理器

    AFHTTPSessionManager *sessionManager = [AFHTTPSessionManager manager];

    sessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"];

    NSString *requestUrlStr = [NSString stringWithFormat:@"%@%@", WEBBASEURL,  WEBInterFace_Personal_UploadHeadImg];

    [sessionManager POST:requestUrlStr parameters:parameterDict constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {

        // 上传文件  服务器对应[file]

        NSData *imageData = UIImageJPEGRepresentation(uploadImage, imageType == 1);

        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];

        formatter.dateFormat = @"yyyyMMddHHmmss";

        NSString *str = [formatter stringFromDate:[NSDate date]];

        NSString *fileName = [NSString stringWithFormat:@"%@%@.jpg", appDelegate.userKeyString, str];

        

        [formData appendPartWithFileData:imageData name:@"headImg"  fileName:fileName mimeType:@"image/jpg"];       // 上传图片的参数key

    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {

        MYLOG(@"success");



    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

        MYLOG(@"failure:%@", error);

    }];

}
上一篇下一篇

猜你喜欢

热点阅读