苹果开发之ios图片上传方法

方法1

在项目中我们经常会遇到需要上传图片的地方,比如更换头像,上传证件照片等.下面介绍一种上传图片的方法.

首先我们需要在项目里打开手机的相册或者相机,然后在下面这个代理方法里进行图片的上传操作.

需要遵循

<UIImagePickerControllerDelegate,UINavigationControllerDelegate>代理.

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info

{

UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];

 

UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);

[self dismissViewControllerAnimated:YES completion:nil];

 

 

self.backBlackView.hidden = YES;

self.carmaChooeView.hidden = YES;

AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] init];

manager.requestSerializer = [AFHTTPRequestSerializer serializer];

[manager.requestSerializer setValue:@”image/png/jpeg/jpg” forHTTPHeaderField:@”Content-Type”];

manager.requestSerializer = [AFJSONRequestSerializer serializer];

manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@”application/json”, @”text/json”, @”text/html”, @”text/javascript”, nil];

NSData *imageData = UIImageJPEGRepresentation(image, 0.5);

NSDictionary *parameter = nil;//这里可以上传一些你需要上传的信息,比如备注等.

AFHTTPRequestOperation *op = [manager POST:kBandCardURL parameters:parameter constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {

[formData appendPartWithFileData:imageData name:@”bank_card_front” fileName:@”photo.jpg” mimeType:@”image/png/jpeg/jpg”];

} success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {

NSLog(@”Success : %@”,[responseObject objectForKey:@”message”]);

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

NSLog(@”Error : %@ *******%@”,operation.responseString,error);

}];

[op start];
 

}

上面是一个简单的例子,如果我们想更好的来做,可以看下面这个图片上传例子。

方法二

iPhone开发中遇到上传图片问题,找到多资料,最终封装了一个类,请大家指点,代码如下

//
//  RequestPostUploadHelper.h
//  demodes
//
//  Created by 张浩 on 13-5-8.
//  Copyright (c) 2013年 张浩. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface RequestPostUploadHelper : NSObject

/**
 *POST 提交 并可以上传图片目前只支持单张
 */
+ (NSString *)postRequestWithURL: (NSString *)url  // IN
                            postParems: (NSMutableDictionary *)postParems // IN 提交参数据集合
                            picFilePath: (NSString *)picFilePath  // IN 上传图片路径
                            picFileName: (NSString *)picFileName;  // IN 上传图片名称

/**
 * 修发图片大小
 */
+ (UIImage *) imageWithImageSimple:(UIImage*)image scaledToSize:(CGSize) newSize;
/**
 * 保存图片
 */
+ (NSString *)saveImage:(UIImage *)tempImage WithName:(NSString *)imageName;
/**
 * 生成GUID
 */
+ (NSString *)generateUuidString;
@end

//
//  RequestPostUploadHelper.m
//  demodes
//
//  Created by 张浩 on 13-5-8.
//  Copyright (c) 2013年 张浩. All rights reserved.
//

#import "RequestPostUploadHelper.h"

@implementation RequestPostUploadHelper

static NSString * const FORM_FLE_INPUT = @"file";

+ (NSString *)postRequestWithURL: (NSString *)url  // IN
                      postParems: (NSMutableDictionary *)postParems // IN
                     picFilePath: (NSString *)picFilePath  // IN
                     picFileName: (NSString *)picFileName;  // IN
{
   
  
    NSString *TWITTERFON_FORM_BOUNDARY = @"0xKhTmLbOuNdArY";
    //根据url初始化request
    NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]
                                                           cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                                                       timeoutInterval:10];
    //分界线 --AaB03x
    NSString *MPboundary=[[NSString alloc]initWithFormat:@"--%@",TWITTERFON_FORM_BOUNDARY];
    //结束符 AaB03x--
    NSString *endMPboundary=[[NSString alloc]initWithFormat:@"%@--",MPboundary];
    //得到图片的data
    NSData* data;
    if(picFilePath){
    
        UIImage *image=[UIImage imageWithContentsOfFile:picFilePath];
        //判断图片是不是png格式的文件
        if (UIImagePNGRepresentation(image)) {
            //返回为png图像。
            data = UIImagePNGRepresentation(image);
        }else {
            //返回为JPEG图像。
            data = UIImageJPEGRepresentation(image, 1.0);
        }
    }
    //http body的字符串
    NSMutableString *body=[[NSMutableString alloc]init];
    //参数的集合的所有key的集合
    NSArray *keys= [postParems allKeys];
   
    //遍历keys
    for(int i=0;i<[keys count];i++)
    {
        //得到当前key
        NSString *key=[keys objectAtIndex:i];
     
        //添加分界线,换行
        [body appendFormat:@"%@\r\n",MPboundary];
        //添加字段名称,换2行
        [body appendFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",key];
        //添加字段的值
        [body appendFormat:@"%@\r\n",[postParems objectForKey:key]];
       
         NSLog(@"添加字段的值==%@",[postParems objectForKey:key]);
    }
   
    if(picFilePath){
    ////添加分界线,换行
        [body appendFormat:@"%@\r\n",MPboundary];
   
        //声明pic字段,文件名为boris.png
        [body appendFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\n",FORM_FLE_INPUT,picFileName];
        //声明上传文件的格式
        [body appendFormat:@"Content-Type: image/jpge,image/gif, image/jpeg, image/pjpeg, image/pjpeg\r\n\r\n"];
    }
   
    //声明结束符:--AaB03x--
    NSString *end=[[NSString alloc]initWithFormat:@"\r\n%@",endMPboundary];
    //声明myRequestData,用来放入http body
    NSMutableData *myRequestData=[NSMutableData data];

    //将body字符串转化为UTF8格式的二进制
    [myRequestData appendData:[body dataUsingEncoding:NSUTF8StringEncoding]];
    if(picFilePath){
        //将image的data加入
        [myRequestData appendData:data];
    }
    //加入结束符--AaB03x--
    [myRequestData appendData:[end dataUsingEncoding:NSUTF8StringEncoding]];
 
    //设置HTTPHeader中Content-Type的值
    NSString *content=[[NSString alloc]initWithFormat:@"multipart/form-data; boundary=%@",TWITTERFON_FORM_BOUNDARY];
    //设置HTTPHeader
    [request setValue:content forHTTPHeaderField:@"Content-Type"];
    //设置Content-Length
    [request setValue:[NSString stringWithFormat:@"%d", [myRequestData length]] forHTTPHeaderField:@"Content-Length"];
    //设置http body
    [request setHTTPBody:myRequestData];
    //http method
    [request setHTTPMethod:@"POST"];
   
   
    NSHTTPURLResponse *urlResponese = nil;
    NSError *error = [[NSError alloc]init];
    NSData* resultData = [NSURLConnection sendSynchronousRequest:request   returningResponse:&urlResponese error:&error];
    NSString* result= [[NSString alloc] initWithData:resultData encoding:NSUTF8StringEncoding];
    if([urlResponese statusCode] >=200&&[urlResponese statusCode]<300){
        NSLog(@"返回结果=====%@",result);
        return result;
    }
    return nil;
}

/**
 * 修发图片大小
 */
+ (UIImage *) imageWithImageSimple:(UIImage*)image scaledToSize:(CGSize) newSize{
    newSize.height=image.size.height*(newSize.width/image.size.width);
    UIGraphicsBeginImageContext(newSize);
    [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
    UIImage *newImage=UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return  newImage;

}

/**
 * 保存图片
 */
+ (NSString *)saveImage:(UIImage *)tempImage WithName:(NSString *)imageName{
    NSData* imageData;
   
    //判断图片是不是png格式的文件
    if (UIImagePNGRepresentation(tempImage)) {
        //返回为png图像。
        imageData = UIImagePNGRepresentation(tempImage);
    }else {
        //返回为JPEG图像。
        imageData = UIImageJPEGRepresentation(tempImage, 1.0);
    }  
    NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
   
    NSString* documentsDirectory = [paths objectAtIndex:0];
   
    NSString* fullPathToFile = [documentsDirectory stringByAppendingPathComponent:imageName];

    NSArray *nameAry=[fullPathToFile componentsSeparatedByString:@"/"];
    NSLog(@"===fullPathToFile===%@",fullPathToFile);
    NSLog(@"===FileName===%@",[nameAry objectAtIndex:[nameAry count]-1]);
   
    [imageData writeToFile:fullPathToFile atomically:NO];
    return fullPathToFile;
}

/**
 * 生成GUID
 */
+ (NSString *)generateUuidString{
    // create a new UUID which you own
    CFUUIDRef uuid = CFUUIDCreate(kCFAllocatorDefault);
   
    // create a new CFStringRef (toll-free bridged to NSString)
    // that you own
    NSString *uuidString = (NSString *)CFUUIDCreateString(kCFAllocatorDefault, uuid);
   
    // transfer ownership of the string
    // to the autorelease pool
    [uuidString autorelease];
   
    // release the UUID
    CFRelease(uuid);
   
    return uuidString;
}
@endDEMO

//
//  UploadViewController.h
//  demodes
//
//  Created by 张浩 on 13-5-6.
//  Copyright (c) 2013年 张浩. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface UploadViewController : UIViewController<UIActionSheetDelegate,UIImagePickerControllerDelegate>
- (IBAction)onClickUploadPic:(id)sender;
- (void) snapImage;//拍照
- (void) pickImage;//从相册里找
- (UIImage *) imageWithImageSimple:(UIImage*)image scaledToSize:(CGSize) newSize;
- (void)saveImage:(UIImage *)tempImage WithName:(NSString *)imageName;
- (IBAction)onPostData:(id)sender;
- (NSString *)generateUuidString;
@end

//
//  UploadViewController.m
//  demodes
//
//  Created by 张浩 on 13-5-6.
//  Copyright (c) 2013年 张浩. All rights reserved.
//

#import "UploadViewController.h"
#import "RequestPostUploadHelper.h"
@interface UploadViewController ()

@end

NSString *TMP_UPLOAD_IMG_PATH=@"";
@implementation UploadViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)onClickUploadPic:(id)sender {
    UIActionSheet *menu=[[UIActionSheet alloc] initWithTitle:@"上传图片" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照上传",@"从相册上传", nil];
    menu.actionSheetStyle=UIActionSheetStyleBlackTranslucent;
    [menu showInView:self.view];
   
}
- (void) actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
     NSLog(@"33333333333333");
    if(buttonIndex==0){
        [self snapImage];
        NSLog(@"111111111111");
    }else if(buttonIndex==1){
        [self pickImage];
        NSLog(@"222222222222");
    }
   
    [actionSheet release];
}
//拍照
- (void) snapImage{
    UIImagePickerController *ipc=[[UIImagePickerController alloc] init];
    ipc.sourceType=UIImagePickerControllerSourceTypeCamera;
    ipc.delegate=self;
    ipc.allowsEditing=NO;
    [self presentModalViewController:ipc animated:YES];
   
}
//从相册里找
- (void) pickImage{
    UIImagePickerController *ipc=[[UIImagePickerController alloc] init];
    ipc.sourceType=UIImagePickerControllerSourceTypePhotoLibrary;
    ipc.delegate=self;
    ipc.allowsEditing=NO;
    [self presentModalViewController:ipc animated:YES];
}

-(void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *) info{
    UIImage *img=[info objectForKey:@"UIImagePickerControllerOriginalImage"];

    if(picker.sourceType==UIImagePickerControllerSourceTypeCamera){
//        UIImageWriteToSavedPhotosAlbum(img,nil,nil,nil);
    }
    UIImage *newImg=[self imageWithImageSimple:img scaledToSize:CGSizeMake(300, 300)];
    [self saveImage:newImg WithName:[NSString stringWithFormat:@"%@%@",[self generateUuidString],@".jpg"]];
    [self dismissModalViewControllerAnimated:YES];
    [picker release];

}
-(UIImage *) imageWithImageSimple:(UIImage*) image scaledToSize:(CGSize) newSize{
    newSize.height=image.size.height*(newSize.width/image.size.width);
    UIGraphicsBeginImageContext(newSize);
    [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
    UIImage *newImage=UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return  newImage;
}

- (void)saveImage:(UIImage *)tempImage WithName:(NSString *)imageName

{
    NSLog(@"===TMP_UPLOAD_IMG_PATH===%@",TMP_UPLOAD_IMG_PATH);
    NSData* imageData = UIImagePNGRepresentation(tempImage);
   
    NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
   
    NSString* documentsDirectory = [paths objectAtIndex:0];
   
    // Now we get the full path to the file
   
    NSString* fullPathToFile = [documentsDirectory stringByAppendingPathComponent:imageName];
   
    // and then we write it out
    TMP_UPLOAD_IMG_PATH=fullPathToFile;
    NSArray *nameAry=[TMP_UPLOAD_IMG_PATH componentsSeparatedByString:@"/"];
    NSLog(@"===new fullPathToFile===%@",fullPathToFile);
    NSLog(@"===new FileName===%@",[nameAry objectAtIndex:[nameAry count]-1]);
   
    [imageData writeToFile:fullPathToFile atomically:NO];
   
}

- (IBAction)onPostData:(id)sender {
    NSMutableDictionary * dir=[NSMutableDictionary dictionaryWithCapacity:7];
    //[dir setValue:@"save" forKey:@"m"];
    [dir setValue:@"IOS上传试试" forKey:@"title"];
    [dir setValue:@"IOS上传试试" forKey:@"content"];
    [dir setValue:@"28" forKey:@"clubUserId"];
    [dir setValue:@"1" forKey:@"clubSectionId"];
    [dir setValue:@"192.168.0.26" forKey:@"ip"];
    [dir setValue:@"asfdfasdfasdfasdfasdfasd=" forKey:@"sid"];
    NSString *url=@"http://192.168.0.26:8090/api/club/topicadd.do?m=save";
    NSLog(@"=======上传");
    if([TMP_UPLOAD_IMG_PATH isEqualToString:@""]){
        [RequestPostUploadHelper postRequestWithURL:url postParems:dir picFilePath:nil picFileName:nil];
    }else{
        NSLog(@"有图标上传");
        NSArray *nameAry=[TMP_UPLOAD_IMG_PATH componentsSeparatedByString:@"/"];
       [RequestPostUploadHelper postRequestWithURL:url postParems:dir picFilePath:TMP_UPLOAD_IMG_PATH picFileName:[nameAry objectAtIndex:[nameAry count]-1]];;
    }
 
}
- (NSString *)generateUuidString
{
    // create a new UUID which you own
    CFUUIDRef uuid = CFUUIDCreate(kCFAllocatorDefault);
   
    // create a new CFStringRef (toll-free bridged to NSString)
    // that you own
    NSString *uuidString = (NSString *)CFUUIDCreateString(kCFAllocatorDefault, uuid);
   
    // transfer ownership of the string
    // to the autorelease pool
    [uuidString autorelease];
   
    // release the UUID
    CFRelease(uuid);
   
    return uuidString;
}
@end

时间: 2025-01-04 20:22:40

苹果开发之ios图片上传方法的相关文章

服务器那边没数据-iOS 图片上传,服务器那边收不到数据,显示字节数为0

问题描述 iOS 图片上传,服务器那边收不到数据,显示字节数为0 /** 上传头像 接口说明 此接接口以POST方式请求. 请求说明http://124.207.188.52/firmail/app/imgupload/upload?uid=111&file=图片二进制流 参数说明 uid 用户id file 图片的二进制流 */ (void)asiUploadIcon { NSURL *url = [NSURL URLWithString:@"http://124.207.188.52

移动端html5图片上传方法【更好的兼容安卓IOS和微信】_Android

之前的移动端上传的方法,有些朋友测试说微信支持不是很好,还有部分安卓机也不支持,其实我已经有了另一个方法,但是例子还没整理出来,而联系我的很多朋友需要,所以就提前先发出来了,并且做一个简单的说明,就不做一个demo了. <!doctype html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=dev

苹果开发之ios 验证码倒计时

第一步,拖两个空间textfiled和button到storyboard上的viewcontroller上. 开发之ios 验证码倒计时-ios开发验证码倒计时"> 第二步,拖线,链接到.h文件中代码如下: @property (weak, nonatomic) IBOutlet UIButton *l_timeButton; 第三步,在,m文件中为l_timeButton设置监听器,监听点击事件. - (void)viewDidLoad {     [super viewDidLoad]

iOS图片上传服务器(ASIHTTPRequest,SpringMVC)

最近开始做自己app的服务器,因为正在参与的公司项目用的是springMVC,干脆拿这个做服务器,iOS端采用第三方鼎鼎大名的ASIHTTPRequest(但是已停更很久),经过一天折腾,终于实现简单的图片上传 配置ASIHTTPRequest,参见 ASIHTTPRequest配置说明 搭建简单的springMVC环境 代码 iOS端: -(void)uploadImgToServer:(UIImage*)image{ ASIFormDataRequest *formDataRequest=[

移动端html5图片上传方法【更好的兼容安卓IOS和微信】

之前的移动端上传的方法,有些朋友测试说微信支持不是很好,还有部分安卓机也不支持,其实我已经有了另一个方法,但是例子还没整理出来,而联系我的很多朋友需要,所以就提前先发出来了,并且做一个简单的说明,就不做一个demo了. <!doctype html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=dev

asp.net图片上传方法

上传图片的相对路径到数据库教程中相应字段里,读取显示时,将控件(假设用的是image控件)的imageurl属性指向该相对路径即可. code: protected void button1_click(object sender, eventargs e)   {   string name = fileupload1.filename;//获取文件名   string type = name.substring(name.lastindexof(".") + 1);       /

苹果开发之iOS 摇一摇动画

微信的摇一摇动画效果看起来很棒,这里是类似的摇一摇动画效果,代码示例:  代码如下 复制代码 #pragma mark - 摇一摇 - (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event {     if (motion == UIEventSubtypeMotionShake) {         AudioServicesPlaySystemSound(kSystemSoundID_Vibrate); //震

苹果开发之iOS加入购物车动画效果

 代码如下 复制代码 #pragma mark -购物篮按钮点击事件 -(void)shoppingCartButtonAction:(UIButton*)sender {     if ([[userDef objectForKey:@"id"]isEqualToString:@"0"]) {         [self showHUDTextOnly:@"请登录后,再进行操作" ];         return;     }     NSD

iOS实现压缩图片上传功能_IOS

本文实例为大家分享了iOS实现压缩图片上传功能,供大家参考,具体内容如下 #pragma mark - 打开相机 -(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{ UIImage *image = info[UIImagePickerControllerOriginalImage]; s