AFNetworking上传图片和视频(支持多张图片上传)


1使用AFNetworking上传图片和视频,支持多张图片上传。以下是AFNetworking用于上传文件的关键函数。

/**

@param  data 图片或视频二进制数据

 @param name 对应服务器的字段名

 @param fileName 文件名,后缀要跟文件类型一致,不能为空

 @param mimeType 文件类型 举例 image/png  video/quicktime

 */

- (void)appendPartWithFileData:(NSData *)data

                          name:(NSString *)name

                      fileName:(NSString *)fileName

                      mimeType:(NSString *)mimeType;


主要实现代码如下:


- (void)uploadFileWithMediaData:(NSMutableArray *)mediaDatas
                          url:(NSString *)url
                        params:(id)params
{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
     manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",
                                                                               @"text/plain",
                                                                               @"application/json",nil];
    
    
    AFHTTPRequestOperation *operation = [manager POST:url
                                           parameters:nil
                            constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
                                
                                if (mediaDatas.count > 0) {
                                    NSObject *firstObj = [mediaDatas objectAtIndexSafe:0];
                                    if ([firstObj isKindOfClass:[UIImage class]]) {     // 图片
                                        for(NSInteger i=0; i<mediaDatas.count; i++) {
                                            UIImage *eachImg = [mediaDatas objectAtIndexSafe:i];
                                            //NSData *eachImgData = UIImagePNGRepresentation(eachImg);
                                            NSData *eachImgData = UIImageJPEGRepresentation(eachImg, 0.5);
                                            [formData appendPartWithFileData:eachImgData name:@"file" fileName:[NSString stringWithFormat:@"img%ld.png", i+1] mimeType:@"image/png"];
                                            
                                        }
                                    }else if([firstObj isKindOfClass:[ALAsset class]]){
                                        
                                        // 视频
                                        ALAsset *asset = [mediaDatas objectAtIndexSafe:0];
                                        NSLog(@"asset=%@, representation=%@, url=%@", asset, [asset defaultRepresentation], [asset defaultRepresentation].url);
                                        if (asset != nil) {
                                            NSArray *documentPaths= NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
                                            NSString *docuPath = [documentPaths objectAtIndex:0];
                                            
                                            NSString *videoPath= [docuPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%d.mov", 0]];    // 这里直接强制写一个即可,之前计划是用i++来区分不明视频
                                            NSURL *url = [NSURL fileURLWithPath:videoPath];
                                            NSError *theErro = nil;
                                            BOOL exportResult = [asset exportDataToURL:url error:&theErro];
                                            NSLog(@"exportResult=%@", exportResult?@"YES":@"NO");
                                            
                                            NSData *videoData = [NSData dataWithContentsOfURL:url];
                                            [formData appendPartWithFileData:videoData name:@"file" fileName:@"video1.mov" mimeType:@"video/quicktime"];
                                        }
                                        
                                    }
                                }
                            } success:^(AFHTTPRequestOperation *operation, id responseObject) {
                                //成功后回调
                                
                                
                            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                                //失败后回调
                            }];
    
    [operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
		//进度
        self.progressBlock(totalBytesWritten*1.0/totalBytesExpectedToWrite);
    }];
}


通过CTAssetsPickerController来选择手机相册中的视频文件的。然后通过生成一个视频文件名及地址, 并通过一个写方法, 写到该路径下, 写文件如下。

#import "ALAsset+mExport.h"

#define BufferSize 10000

@implementation ALAsset (mExport)

- (BOOL) exportDataToURL: (NSURL*) fileURL error: (NSError**) error
{
    [[NSFileManager defaultManager] createFileAtPath:[fileURL path] contents:nil attributes:nil];
    NSFileHandle *handle = [NSFileHandle fileHandleForWritingToURL:fileURL error:error];
    if (!handle) {
        return NO;
    }
    
    ALAssetRepresentation *rep = [self defaultRepresentation];
    uint8_t *buffer = calloc(BufferSize, sizeof(*buffer));
    NSUInteger offset = 0, bytesRead = 0;
    
    do {
        @try {
            bytesRead = [rep getBytes:buffer fromOffset:offset length:BufferSize error:error];
            [handle writeData:[NSData dataWithBytesNoCopy:buffer length:bytesRead freeWhenDone:NO]];
            offset += bytesRead;
        } @catch (NSException *exception) {
            free(buffer);
            return NO;
        }
    } while (bytesRead > 0);
    
    free(buffer);
    return YES;
}

@end


                                    

你可能感兴趣的:(ios,文件上传,AFNetworking,图片上传,视频上传)