后台我使用的是php语言,你们也可以换成其他的语言
此种上传为模拟HTML表单上传 火狐浏览器firebug上抓取请求头的数据进行拼接
上代码ing。。。
//
// ViewController.m
// POST原始的模拟表单上传
//
// Created by chen on 15/2/16.
// Copyright (c) 2015年 lanrw. All rights reserved.
//
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[self uploadFile];
}
- (void)uploadFile
{
// 拼接以下请求
/**
Content-Typemultipart/form-data; boundary=8116616557813098411759479929
--8116616557813098411759479929
Content-Disposition: form-data; name="userfile"; filename="upload.html"
Content-Type: text/html
文件上传测试文件上传
请选择要上传的文件:
--8116616557813098411759479929--
*/
// 自己建立一个php后端的服务器
NSURL *url = [NSURL URLWithString:@"http://localhost/post/upload.php"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:1 timeoutInterval:15];
request.HTTPMethod = @"post";
// boundary可随意命名
NSString *boundary = @"chen";
// 拼接请求头
[request setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary] forHTTPHeaderField:@"Content-Type"];
// 创建可变data 后面一样拼接
NSMutableData *myData = [NSMutableData data];
NSString *str = [NSString stringWithFormat:@"--%@\n",boundary];
[myData appendData:[str dataUsingEncoding:NSUTF8StringEncoding]];
// html页面上传表单里的
NSString *name = @"userfile";
// 上传后文件的名字
NSString *filename = @"123.png";
str = [NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\n",name,filename];
[myData appendData:[str dataUsingEncoding:NSUTF8StringEncoding]];
str = @"Content-Type: application/octet-stream\n\n";
[myData appendData:[str dataUsingEncoding:NSUTF8StringEncoding]];
// bundle中的文件转换成二进制数据
NSURL *uploadFile = [[NSBundle mainBundle]URLForResource:@"000.png" withExtension:nil];
[myData appendData:[NSData dataWithContentsOfURL:uploadFile]];
str = [NSString stringWithFormat:@"\n\n--%@--",boundary];
[myData appendData:[str dataUsingEncoding:NSUTF8StringEncoding]];
request.HTTPBody = myData;
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
id result = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
NSLog(@"%@",result);
}];
}
@end
http://pan.baidu.com/s/1eQCMbdS