我需要将文件上传到我们的服务器。但是,服务器将处理该文件并将其激发到数据库中。我看NSInputStream
似乎工作正常,但是,我还需要其他参数,如用户令牌和文件扩展名,我不知道如何实现这一点。我可以使用HTTPBodyStream
作为流本身,但是该方法抱怨并非所有参数都被提供。我使用的代码如下,基于我将数据发布到Web方法的其他区域。
- (IBAction)uploadFile:(id)sender {
// File will be replaced in production with selected file from resources directory
NSString* path = [[NSBundle mainBundle] pathForResource:@"myFile"
ofType:@"docx"];
NSInputStream *stream = [[NSInputStream alloc] initWithFileAtPath:path];
// JSON Method
NSURL *uploadURL = [NSURL URLWithString:@"myDomain/myMethod"];
NSDictionary *requestDict = [[NSDictionary alloc] initWithObjectsAndKeys:
@"userTokenValue", @"userToken",
stream,@"fileStream",
@"docx", @"fileExt",
nil];
NSError *error;
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:requestDict options:NSJSONReadingMutableContainers|NSJSONReadingAllowFragments error:&error];
NSString *json=[[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
NSData *postData=[NSData dataWithBytes:[json UTF8String] length:[json length]];
request = [[NSMutableURLRequest alloc] initWithURL:uploadURL];
// Allows all parameters to be sent in other calls in the app, however generates SIGABRT here - detail below
[request setHTTPBody:postData];
// Reaches method, but method complains that not all parameters are supplied obviously
[request setHTTPBodyStream:stream];
[request setHTTPMethod:@"POST"];
NSError *requestError=nil;
NSURLResponse *response = nil;
NSData *data=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&requestError];
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
if (requestError == nil) {
if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
NSInteger statusCode = [(NSHTTPURLResponse *)response statusCode];
if (statusCode != 200) {
NSLog(@"Warning, status code of response was not 200, it was %ld", (long)statusCode);
}
}
NSError *error;
NSDictionary *returnDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
if (returnDictionary) {
NSLog(@"returnDictionary=%@", returnDictionary);
} else {
NSLog(@"error parsing JSON response: %@", error);
NSString *returnString = [[NSString alloc] initWithBytes:[data bytes] length:[data length] encoding:NSUTF8StringEncoding];
NSLog(@"returnString: %@", returnString);
}
} else {
NSLog(@"NSURLConnection sendSynchronousRequest error: %@", requestError);
}
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
上面提到的SIGABRT是:
' NSInvalidArgumentException',原因:' JSON写入中的无效类型(__NSCFInputStream)'
如何通过Web方法传输文件数据以及提供其他参数。谢谢。