将图像的base64String和其他参数发布到服务器Objective c

时间:2018-09-18 13:45:58

标签: ios objective-c post base64

我有图片,我需要将该图片和其他参数发送到服务器。

我将图像转换为base64字符串。

  

[UIImagePNGRepresentation(图像)   base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];

我在标头参数中发送此邮件。

  

“ Content-Type” =“应用程序/ x-www-form-urlencoded”;

     

NSURLSessionDataTask * task = [session dataTaskWithRequest:self   completeHandler:^(NSData * _Nullable数据,NSURLResponse * _Nullable   响应,NSError * _Nullable错误){....}

这是我的参数格式

data={"img":"","imgName":"imgName"}

当我发送“ img”:“ iVBORw0KGgoAAAANSUhEUgAAAZUA ..” 时,我收到 401 错误

如果有人发现问题,或者知道如何使用其他参数发送base64字符串,请帮助我。谢谢!

1 个答案:

答案 0 :(得分:0)

尝试一下。

UIImage *image = yourImage;
NSString *imageBase64Str = [NSString stringWithFormat:@"%@;base64,%@",
 [self mimeTypeByGuessingFromData:imageData], [self encodeToBase64String:image]];

data = {“ doc”:“ true”,“ img”:“ imageBase64Str”,“ imgName”:“ imgName”}

- (NSString *)mimeTypeByGuessingFromData:(NSData *)data {
    char bytes[12] = {0};
    [data getBytes:&bytes length:12];
    const char bmp[2] = {'B', 'M'};
    const char gif[3] = {'G', 'I', 'F'};
    const char swf[3] = {'F', 'W', 'S'};
    const char swc[3] = {'C', 'W', 'S'};
    const char jpg[3] = {0xff, 0xd8, 0xff};
    const char psd[4] = {'8', 'B', 'P', 'S'};
    const char iff[4] = {'F', 'O', 'R', 'M'};
    const char webp[4] = {'R', 'I', 'F', 'F'};
    const char ico[4] = {0x00, 0x00, 0x01, 0x00};
    const char tif_ii[4] = {'I','I', 0x2A, 0x00};
    const char tif_mm[4] = {'M','M', 0x00, 0x2A};
    const char png[8] = {0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a};
    const char jp2[12] = {0x00, 0x00, 0x00, 0x0c, 0x6a, 0x50, 0x20, 0x20, 0x0d, 0x0a, 0x87, 0x0a};
    if (!memcmp(bytes, bmp, 2)) {
        return @"image/x-ms-bmp";
    } else if (!memcmp(bytes, gif, 3)) {
        return @"image/gif";
    } else if (!memcmp(bytes, jpg, 3)) {
        return @"image/jpeg";
    } else if (!memcmp(bytes, psd, 4)) {
        return @"image/psd";
    } else if (!memcmp(bytes, iff, 4)) {
        return @"image/iff";
    } else if (!memcmp(bytes, webp, 4)) {
        return @"image/webp";
    } else if (!memcmp(bytes, ico, 4)) {
        return @"image/vnd.microsoft.icon";
    } else if (!memcmp(bytes, tif_ii, 4) || !memcmp(bytes, tif_mm, 4)) {
        return @"image/tiff";
    } else if (!memcmp(bytes, png, 8)) {
        return @"image/png";
    } else if (!memcmp(bytes, jp2, 12)) {
        return @"image/jp2";
    }
    return @"application/octet-stream"; // default type
}

- (NSString *)encodeToBase64String:(UIImage *)image {
    return [UIImagePNGRepresentation(image) base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
}