使用 NSURLSession 上传文件

问题描述 投票:0回答:1

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

- (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);
}

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

ios iphone file-upload ios7 nsurlsession
1个回答
0
投票

如果您使用 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! */ }
}
© www.soinside.com 2019 - 2024. All rights reserved.