ios中的表单的传递

这个确实是弄了好久,纠结了好久,在网上借鉴了这个方法,在这浪费了太多的时间,分享给大家,少走弯路吧……


这个自己定义的

//  RequestPostUploadHelper.h

//  PocketIdol1

//

//  Created by  on 16/1/22.

//  Copyright © 2016 . All rights reserved.

//


#import <Foundation/Foundation.h>

#import <UIKit/UIKit.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

//  PocketIdol1

//

//  Created by  on 16/1/22.

//  Copyright © 2016 . All rights reserved.

//


#import "RequestPostUploadHelper.h"


@implementation RequestPostUploadHelper

static NSString * const FORM_FLE_INPUT = @"upimg";//与服务器要求的key 一样


+ (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 = [NSMutableURLRequestrequestWithURL:[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=[UIImageimageWithContentsOfFile: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",[postParemsobjectForKey: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"];

        NSLog(@"body = %@",body);

    }

    

    //声明结束符:--AaB03x--

    NSString *end=[[NSStringalloc]initWithFormat:@"\r\n%@",endMPboundary];

    //声明myRequestData,用来放入http body

    NSMutableData *myRequestData=[NSMutableData data];

    

    //body字符串转化为UTF8格式的二进制

    [myRequestData appendData:[bodydataUsingEncoding:NSUTF8StringEncoding]];

    if(picFilePath){

        //imagedata加入

        [myRequestData appendData:data];

    }

    //加入结束符--AaB03x--

    [myRequestData appendData:[enddataUsingEncoding:NSUTF8StringEncoding]];

    

    //设置HTTPHeaderContent-Type的值

    NSString *content=[[NSStringalloc]initWithFormat:@"multipart/form-data; boundary=%@",TWITTERFON_FORM_BOUNDARY];

    //设置HTTPHeader

    [request setValue:content forHTTPHeaderField:@"Content-Type"];

    //设置Content-Length

    [request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)[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 = [NSURLConnectionsendSynchronousRequest:request   returningResponse:&urlResponeseerror:&error];

    NSString* result= [[NSString allocinitWithData:resultDataencoding: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(00, 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 = [documentsDirectorystringByAppendingPathComponent:imageName];

    

    NSArray *nameAry=[fullPathToFilecomponentsSeparatedByString:@"/"];

    NSLog(@"===fullPathToFile===%@",fullPathToFile);

    NSLog(@"===FileName===%@",[nameAry objectAtIndex:[nameArycount]-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



要调用时用的

//  PhoneVideoViewController.m

//  PocketIdol1

//

//  Created by  on 16/1/13.

//  Copyright © 2016 . All rights reserved.


#import "PhoneVideoViewController.h"

@interface PhoneVideoViewController ()<UITableViewDataSource,UITableViewDelegatePhoneVideoTableViewCellDelegate>


@end

NSString *TMP_UPLOAD_IMG_PATH=@"";



这个方法是点击提交按钮后传值到viewcontroller的    《延展传值》

- (void)pushVideoPicWithUping:(UIImage *)uping withTimes:(NSString *)time withSign:(NSString *)sign withDesscription:(NSString *)description withVideodesc:(NSString *)videodesc withVideourl:(NSString *)videourl {

    

 

    NSLog(@"pic = %@",self.picString);//这个是传过来的图片UIimage  

//数据传给服务器的参数,没有图片,添加到字典里    post传值   

    [self.params setValue:time forKey:@"time"];

    [self.params setValue:[[FileHandle shareInstanceuserid]forKey:@"userid"];

    [self.params setValue:sign forKey:@"sign"];

    [self.params setValue:description forKey:@"description"];

    [self.params setValue:videodesc forKey:@"videodesc"];

    [self.params setValue:videourl forKey:@"videourl"];

    


    NSDateFormatter *formatter = [[NSDateFormatter allocinit];

    formatter.dateFormat = @"yyyyMMddHHmmss";

    NSString *str = [formatter stringFromDate:[NSDate date]];

    NSString *fileName = [NSString stringWithFormat:@"%@.png", str];

    NSLog(@"%@", fileName);

 


    //上传的接口

    NSString *urlStr = @"你的url服务器地址";

//对图片进行处理

  NSData* imageData = UIImagePNGRepresentation(self.picString);

    NSArray* paths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);

    NSString* documentsDirectory = [paths objectAtIndex:0];

    

    // Now we get the full path to the file

    

    NSString* fullPathToFile = [documentsDirectorystringByAppendingPathComponent:fileName];

    

    // and then we write it out

    TMP_UPLOAD_IMG_PATH=fullPathToFile;

    NSArray *nameAry=[TMP_UPLOAD_IMG_PATHcomponentsSeparatedByString:@"/"];


    NSLog(@"===new FileName===%@",[nameAry objectAtIndex:[nameArycount]-1]);

    NSString *file = fullPathToFile;


    [imageData writeToFile:fullPathToFile atomically:NO];


    NSLog(@"有图标上传时调用下面的方法");

    nameAry=[TMP_UPLOAD_IMG_PATHcomponentsSeparatedByString:@"/"];

    [RequestPostUploadHelper postRequestWithURL:urlStrpostParems:self.params picFilePath:file picFileName:[nameAryobjectAtIndex:[nameAry count]-1]];

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值