我想上傳以下方法文件:上傳文件,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);
}
但我總是從我的服務器出現錯誤,有不是一個附件文件!怎麼了?
上傳完成 –
您的HTTP請求的內容類型必須是多/表單數據後如何檢查校驗和。此外,身體必須作爲多部分請求形成。你可以在這裏找到一個教程:http://web.archive.org/web/20140311092840/http://zcentric.com/2008/08/29/post-a-uiimage-to-the-web/ – Janos
看起來好,但如何在這裏獲得動態NSSTrings到文件名:[body appendData:[[NSString stringWithString:@「Content-Disposition:form-data; name =」userfile「; filename =」ipodfile.jpg「rn」] dataUsingEncoding:NSUTF8StringEncoding ]]; – davidOhara