//原文地址http://www.cnblogs.com/skyblue/archive/2013/05/08/3067108.html,因为以后要用到,搬来存下
//
// 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

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

  1. IOS上传图片方法类

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

  2. ios上传图片显示方向错误问题

    IOS 上传图片方向显示错误问题 问题描述 在使用苹果手机上传图片的时候,发现传完的图片显示出来方向是错误的,竖着的图片会变成横着显示(少部分安卓手机也存在这个问题) 产生原因 ios 相机加入了方向 ...

  3. iOS上传图片详解

    iphone中图像通常存储在4个地方[相册.应用程序包.沙盒.Internet],通过这4个源,我们就可以存取应用图片. 相册 iphone的相册包含摄像头胶卷+用户计算机同步的部分照片.用户可以通过 ...

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

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

  5. 微信网页IOS上传图片旋转解决方案

    <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title> ...

  6. vue iOS上传图片file 出错

    前言 用vue 移动端上传图片在低版本的 ios 手机上 图片转换base64 在转换file 文件类型 会报错 并且报错 “Script Error ” 查阅了github 和一些文档发现 可以吧 ...

  7. iOS上传图片问题

    今天一定得写一篇博客,有以下原因: 1>第一次做图片上传的功能,算是一种记录吧; 2>在这个问题上,纠结,迷茫了很久,主要还是被后台坑了; 1.上传图片的方法是用的AFNetWorking ...

  8. IOS上传图片方向问题

    在显示上传完毕的图片的时候遇到了一个问题, 图片莫名其妙被逆时针旋转了90度就很离谱 如下图 经过一番查询, 原来是 IOS 的相机拍照的时候会把方向角写入到图片里面 因为我用的是 element 的 ...

  9. ios上传图片遇见了一个TimeoutError(DOM Exception 23)异常

    TimeoutError(DOM Exception 23):The operation timed out 百度了下,没发现解决办法

随机推荐

  1. 第四周 技术随笔psp

    本周psp 类型 内容 开始时间 结束 打断时间 净时间 写随笔 Scrum会议 23:46 00:27 0 41分

  2. jquery json 操作(转)

    原文:http://www.vososo.com/?p=919 Jquery-json 是 jQuery 的一个插件,可轻松实现对象和 JSON 字符串之间的转换.可序列化 JavaScript 对象 ...

  3. long型转日期型

    //时分秒格式//不知为何,出来的时间有点差别 public class Test { public static void main(String[] args) throws Exception ...

  4. QQ输入法评价

    用户界面: 用户可以通过登录QQ展现自己的QQ头像,可以点击头像显示用户信息,可以中英文切换,全半角切换,打开属性设置,以为软键盘 记住用户选择: 当用户使用QQ输入法时,QQ输入法可以记住用户当前的 ...

  5. 15个让人惊讶的 CSS3 动画效果演示

    CSS 是网页设计非常重要的一部分,随着越来越多的浏览器对 CSS3 支持的不断完善,设计师和开发者们有了更多的选择.如今,用纯 CSS 就可以实现各种各样很酷的效果,甚至是动画. 本文收集了15个惊 ...

  6. Storm(1) - Setting Up Development Environment

    Setting up your development environment 1. download j2se 6 SDK from http://www.oracle.com/technetwor ...

  7. Oracle 中的 decode

    含义解释:decode(条件,值1,返回值1,值2,返回值2,...值n,返回值n,缺省值) 该函数的含义如下:IF 条件=值1 THEN RETURN(翻译值1)ELSIF 条件=值2 THEN R ...

  8. 一个QMLListView的例子--

    一般人不知道怎么去过滤ListView里面的数据,下面是一个转载的文章:http://imaginativethinking.ca/use-qt-quicks-delegatemodelgroup/ ...

  9. 转载:完全卸载oracle11g步骤

    完全卸载oracle11g步骤: 1. 开始->设置->控制面板->管理工具->服务 停止所有Oracle服务. 2. 开始->程序->Oracle - OraHo ...

  10. 3D开发的基本知识

    为了实现3D图形,程序员需要定义两个方面的数据: 1.3D图形的每个顶点(Vertex)的位置,每个顶点的位置都需要X.Y.Z三个左标值. 2.3D图形每个面由哪些顶点组成. Android的3D坐标 ...