你好,歡迎來到IOS教程網

 Ios教程網 >> IOS使用技巧 >> IOS7技巧 >> 蘋果開發之ios圖片上傳方法

蘋果開發之ios圖片上傳方法

編輯:IOS7技巧
蘋果開發之ios圖片上傳功能只要做app幾乎都會要用到,這裡整理了兩個例子一個是相對簡單的,另一個是非常的完整不錯的可以直接使用的圖片上傳類。


方法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

  1. 上一頁:
  2. 下一頁:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © Ios教程網 All Rights Reserved