博客> anf以文件方式上传图片
anf以文件方式上传图片
2020-02-26 08:21 评论:0 阅读:1142 dongcaili2012
ios

相册选择图片或者是相机拍照后,显示并把图片以文件的方式上传到服务器 在imagePicker的代理方法- (void)imagePickerController:(UIImagePickerController )picker didFinishPickingMediaWithInfo:(NSDictionary )info { //原图显示 UIImage image = [info objectForKey: UIImagePickerControllerOriginalImage]; NSString filePath = [self getImagePath:image]; [self uploadCoverIamgeWithPath:filePath]; }

//照片获取本地路径 -(NSString )getImagePath:(UIImage )Image {

NSString * filePath = nil;
NSData * data = nil;

if (UIImagePNGRepresentation(Image) == nil) {
    data = UIImageJPEGRepresentation(Image, 1);
} else {
    data = UIImagePNGRepresentation(Image);
}

//图片保存的路径
//这里将图片放在沙盒的documents文件夹中
NSString * DocumentsPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
//文件管理器
NSFileManager *fileManager = [NSFileManager defaultManager];
//把刚刚图片转换的data对象拷贝至沙盒中

//为了防止重命名,添加上时间
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"yyyyMMddHHmmss";
NSString *str = [formatter stringFromDate:[NSDate date]];
[fileManager createDirectoryAtPath:DocumentsPath withIntermediateDirectories:YES attributes:nil error:nil];
NSString * ImagePath = [[NSString alloc]initWithFormat:@"/theCoverImage%@.png",str];
[fileManager createFileAtPath:[DocumentsPath stringByAppendingString:ImagePath] contents:data attributes:nil];

//得到选择后沙盒中图片的完整路径
filePath = [[NSString alloc]initWithFormat:@"%@%@",DocumentsPath,ImagePath];
return filePath;

}

//带参数上传图片

  • (void)uploadCoverIamgeWithPath:(NSString )path{ AFHTTPRequestOperationManager manager = [AFHTTPRequestOperationManager manager];

    manager.requestSerializer = [AFHTTPRequestSerializer serializer];//一定要写

    manager.responseSerializer = [AFHTTPResponseSerializer serializer];

    NSDictionary *dic = @{ @"objectId":@"9128409", @"key":@"b3RoZXJfcGljX2tleQ==", @"upType":@"1", @"channelCode":@"3" };

    [manager POST:API_UploadImage parameters:dic constructingBodyWithBlock:^(idformData) {

    [formData appendPartWithFileURL:[NSURL fileURLWithPath:path] name:@"file" error:nil];

    } success:^(AFHTTPRequestOperation *operation, id responseObject) { //图片上传成功

    } failure:^(AFHTTPRequestOperation _Nonnull operation, NSError _Nonnull error) { //图片上传失败 }];

}

收藏
0
sina weixin mail 回到顶部