IOS上传图片方法类

 
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;
}
@end

DEMO

//
// 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
原文:http://www.cnblogs.com/skyblue/archive/2013/05/08/3067108.html

IOS上传图片方法类的更多相关文章

  1. iOS上传图片和视频(base64和file)

    前言:iOS开发中经常会使用到图片和视频上传及保存到相册,下面我讲介绍视频图片的两种上传服务器的方法.以阿里云的OSS服务器为例. 友情提示:上传图片方法在APP中使用很广泛,最好单独写一个图片上传的 ...

  2. iOS 工厂方法模式

    iOS工厂方法模式 什么是工厂方法模式? 工厂方法模式和简单工厂模式十分类似,大致结构是基本类似的.不同在于工厂方法模式对工厂类进行了进一步的抽象,将之前的一个工厂类抽象成了抽象工厂和工厂子类,抽象工 ...

  3. iOS文件处理类

    iOS文件处理类 这是一个用来简化iOS中关于文件操作的一个类,所有方法都为类方法. Source File.h // // File.h // FileManager // // http://ho ...

  4. php操作oracle的方法类集全

    在网上开始找php中操作oracle的方法类~ 果然找到一个用php+oracle制作email表以及插入查询的教程,赶忙点开来看,从头到尾仔细的看了一遍,还没开始操作,便觉得收获很大了.地址在此:h ...

  5. C#导出数据到Excel通用的方法类

    导出数据到Excel通用的方法类,请应对需求自行修改. 资源下载列表 using System.Data; using System.IO; namespace IM.Common.Tools { p ...

  6. iOS 处理方法中的可变參数

    ## iOS 处理方法中的可变參数 近期写了一个自己定义的对话框的demo,想模仿系统的UIAlertView的实现方式.对处理可变參数的时候,遇到了小问题,于是谷歌了一下.写下了处理问题的方法.记录 ...

  7. idea live template高级知识, 进阶(给方法,类,js方法添加注释)

    为了解决用一个命令(宏)给方法,类,js方法添加注释,经过几天的研究.终于得到结果了. 实现的效果如下: 给Java中的method添加方法: /** * * @Method : addMenu * ...

  8. 【iOS】Swift类的继承、构造方法、析构器等复习

    一.继承与重写, 防止重写 1.1 基类, 不继承任何类. Swift不想OC或者Java中继承自Object类.定义一个类,不继承任何类,该类就是基类. [java] view plaincopy ...

  9. html与ios交互方法 WebViewJavascriptBridge

    WebViewJavascriptBridge 1.html调用ios的方法 <!DOCTYPE html> <html lang="en"> <he ...

随机推荐

  1. TypeError: not all arguments converted during string formatting

    print ("So, you're 5r old, %r tall and %r heavy." % (age, height, weight)) print ("So ...

  2. Python学习笔记——数据结构和算法(二)

    1.字典中一个键映射多个值 可以使用collections中的defaultdict来实现,defalultdict接受list或者set为参数 from collections import def ...

  3. bash: composer: command not found

    下载composer到本地:curl -sS https://getcomposer.org/installer | php 移动至系统服务:sudo mv composer.phar /usr/bi ...

  4. [ python ] FTP作业进阶

    作业:开发一个支持多用户在线的FTP程序 要求: 用户加密认证 允许同时多用户登录 每个用户有自己的家目录 ,且只能访问自己的家目录 对用户进行磁盘配额,每个用户的可用空间不同 允许用户在ftp se ...

  5. 常见的 JavaScript 内存泄露

    什么是内存泄露 指由于疏忽或错误造成程序未能释放已经不再使用的内存.内存泄漏并非指内存在物理上的消失, 而是应用程序分配某段内存后,由于设计错误,导致在释放该段内存之前就失去了对该段内存的控制,从而造 ...

  6. 并发queue

    在并发队列上JDK提供了两套实现,一个是以ConcurrentLinkedQueue为代表的高性能队列,一个是以BlockingQueue接口为代表的阻塞队列,无论哪种都继承自Queue. 一.Con ...

  7. loadrunner获取毫秒及字符串替换实现

    loadrunner获取毫秒及字符串替换实现 今天做一个性能测试,参数化要求创建用户名不可以重复,想来想不没有什么好的办法来避免用户名字的重复.所以就想用时间+随机数来实现,但是实现中遇到一个问题. ...

  8. jquery的一个模板引擎-zt

    jQuery-jTemplate.js下载:http://jtemplates.tpython.com/ 一 , 简单介绍 它是一个基于jQuery开发的javascript模板引擎.它主要的作用如下 ...

  9. vue-music 关于搜索历史本地存储

    搜索历史 搜索过的关键词 保存在本地存储 localstorage 中,同时多个组件共享搜索历史数据,将数据存到vuex 中,初始值从本地缓存中取得对应key 的值,没有数据默认为空数组 点击搜索关键 ...

  10. 洛谷P2296 寻找道路 [拓扑排序,最短路]

    题目传送门 寻找道路 题目描述 在有向图G 中,每条边的长度均为1 ,现给定起点和终点,请你在图中找一条从起点到终点的路径,该路径满足以下条件: 1 .路径上的所有点的出边所指向的点都直接或间接与终点 ...