iOS 图片上传服务器

作者: 天明依旧 | 来源:发表于2016-01-12 11:10 被阅读7009次

    最近搞图片上传,折腾了一个星期终于做出来了,网上搜出来的方法几乎都是好几年前的,试了好多都不能用,此次把代码公布出来供大家参考。

    注:部分代码是后台写的,此方法没用到第三方库。

    1.图片保存到本地同时上传服务器

    (void)saveImage:(UIImage *)image {

    //NSLog(@“保存头像!”);

    //[userPhotoButton setImage:image forState:UIControlStateNormal];

    BOOL success;

    NSFileManager *fileManager = [NSFileManager defaultManager];

    NSError *error;

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

    NSString *documentsDirectory = [paths objectAtIndex:0];

    NSString *imageFilePath = [documentsDirectory stringByAppendingPathComponent:@“selfPhoto.jpg”];

    NSLog(@“imageFile->>%@”,imageFilePath);

    success = [fileManager fileExistsAtPath:imageFilePath];

    if(success) {

    success = [fileManager removeItemAtPath:imageFilePath error:&error];

    }

    //UIImagesmallImage=[self scaleFromImage:image toSize:CGSizeMake(80.0f, 80.0f)];//将图片尺寸改为8080

    UIImage *smallImage = [self thumbnailWithImageWithoutScale:image size:CGSizeMake(93, 93)];

    [UIImageJPEGRepresentation(smallImage, 1.0f) writeToFile:imageFilePath atomically:YES];//写入文件

    UIImage *selfPhoto = [UIImage imageWithContentsOfFile:imageFilePath];//读取图片文件

    self.img.image = selfPhoto;

    NSLog(@“selfPhoto = %@”,selfPhoto);

    NSURL * url = [NSURL URLWithString:@"http://blog.sina.com.cn/tmyij"];

    NSData *imageData = UIImageJPEGRepresentation(selfPhoto,1.0f);

    [self uploadFileWithURL:url data:imageData];

    }

    2.下面俩个方法都是设置请求参数

    static NSString *boundaryStr = @"–";

    static NSStringrandomIDStr = @"****";

    static NSString *uploadID = @“file”;

    (NSString *)topStringWithMimeType:(NSString *)mimeType uploadFile:(NSString *)uploadFile

    {

    NSMutableString *strM = [NSMutableString string];

    [strM appendFormat:@"%@%@\r\n", boundaryStr, randomIDStr];

    [strM appendFormat:@“Content-Disposition: form-data; name=”%@"; filename="%@"\r\n", uploadID, uploadFile];

    [strM appendFormat:@“Content-Type: %@\r\n”, mimeType];

    [strM appendFormat:@"\r\n"];

    NSLog(@"%@", strM);

    return [strM copy];

    }

    (NSString *)bottomString

    {

    NSMutableString *strM = [NSMutableString string];

    [strM appendFormat:@"%@%@\r\n", boundaryStr, randomIDStr];

    [strM appendString:@“Content-Disposition:form-data; name=“number”\r\n”];

    [strM appendFormat:@"\r\n"];

    [strM appendString:@“1234566788”];//上传的参数parameter

    [strM appendFormat:@"\r\n"];

    NSLog(@"%@", strM);

    return [strM copy];

    }

    3.图片上传服务器

    (void)uploadFileWithURL:(NSURL *)url data:(NSData *)data

    {

    NSString *topStr = [self topStringWithMimeType:@“application/img” uploadFile:@“myHead.jpg”];

    NSString *bottomStr = [self bottomString];

    NSMutableData *dataM = [NSMutableData data];

    [dataM appendData:[bottomStr dataUsingEncoding:NSUTF8StringEncoding]];

    [dataM appendData:[topStr dataUsingEncoding:NSUTF8StringEncoding]];

    [dataM appendData:data];

    [dataM appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

    NSString * s = [NSString stringWithFormat:@"%@%@%@\r\n",boundaryStr, randomIDStr, boundaryStr];

    [dataM appendData:[str22 dataUsingEncoding:NSUTF8StringEncoding]];

    NSLog(@"%@%@%@",topStr,data,bottomStr);

    // 1. Request

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:0 timeoutInterval:20.0f];

    request.HTTPBody = dataM;

    request.HTTPMethod = @“POST”;

    NSString *strLength = [NSString stringWithFormat:@"%ld", (long)dataM.length];

    [request setValue:strLength forHTTPHeaderField:@“Content-Length”];

    NSString *strContentType = [NSString stringWithFormat:@“multipart/form-data;boundary=%@”, randomIDStr];

    [request setValue:strContentType forHTTPHeaderField:@“Content-Type”];

    [NSURLConnection sendAsynchronousRequest:request

    queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse

    *response, NSData *data, NSError *connectionError) {

    NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

    NSLog(@"%@", result);

    }];

    }

    相关文章

      网友评论

      • PGOne爱吃饺子:大哥 就凭你没有用到第三方的库,我就要给你一个赞
      • 长满皱纹的歌:不会MarkDown的程序员 :cold_sweat:
        布呐呐u:你行尼桑:blush:
      • 龙雨沫: NSString *imageFilePath = [documentsDirectory stringByappendingPathComponent:@"selfPhoto.jpg"];
        NSLog(@"imageFile->>%@",imageFilePath);(怎么会报错)
      • 龙雨沫: NSString *imageFilePath = [documentsDirectory stringByappendingPathComponent:@"selfPhoto.jpg"];
        NSLog(@"imageFile->>%@",imageFilePath);
      • 华之曦:哥们儿,换成MarkDown编辑下吧,看着实在别扭。
        席坤:@BerrySang 有相关代码?
        华之曦:@BerrySang 简书自带的有MD模式,切换下就可以。
        BerrySang:@Huazhixi 估计不会,我也不会,怎么MarkDown编辑,??

      本文标题:iOS 图片上传服务器

      本文链接:https://www.haomeiwen.com/subject/xzsmhttx.html