使用NSURLSession上载文件

时间:2014-01-23 15:17:00

标签: ios iphone file-upload ios7 nsurlsession

我正在尝试使用以下方法上传文件:

- (void)uploadWithTarget:(NSString *)url andFileData:(NSData *)file andMD5Checksum:(NSString *)checksum
 {


NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: self delegateQueue: [NSOperationQueue mainQueue]];

NSURL * urll = [NSURL URLWithString:url];
NSMutableURLRequest * urlRequest = [NSMutableURLRequest requestWithURL:urll];
[urlRequest setHTTPMethod:@"POST"];
[urlRequest addValue:checksum forHTTPHeaderField:@"Md5Hash"];
[urlRequest addValue:@"Keep-Alive" forHTTPHeaderField:@"Connection"];
[urlRequest addValue:@"xml" forHTTPHeaderField:@"Content-Type"];
[urlRequest setHTTPBody:file];


NSURLSessionDataTask * dataTask = [defaultSession dataTaskWithRequest:urlRequest];
[dataTask resume];


}

代表:

- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask
didReceiveData:(NSData *)data
{
NSString * str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"Received String %@",str);
}

但我总是从我的服务器得到错误,没有附加文件!怎么了?

1 个答案:

答案 0 :(得分:1)

如果您使用的是Swift,请结帐Just。自述文件中的示例:

//  talk to registration end point
Just.post(
    "http://justiceleauge.org/member/register",
    data: ["username": "barryallen", "password":"ReverseF1ashSucks"],
    files: ["profile_photo": .URL(fileURLWithPath:"flash.jpeg", nil)]
) { (r)
    if (r.ok) { /* success! */ }
}