Heim > Fragen und Antworten > Hauptteil
想用ASIHttpRequest上传一个.stl的文件,几十K到70M之间的文件,用的下面这段代码
[uploadFile removeObjectAtIndex:0];//删除mac文件下的默认的.DS_Store
NSString *upFilePath = [NSString stringWithFormat:@"%@/%@",filePath,uploadFile[0]];//上传的文件全路径
ASIFormDataRequest *request=[ASIFormDataRequest requestWithURL:[NSURL URLWithString:@"xxxxx"]];
[request setRequestMethod:@"Post"];
[request addRequestHeader:DownLoad_TOKEN value:@"X-Auth-Token"];
[request setFile:filePath forKey:@"file"];
[request setDelegate:self];
[request startAsynchronous];
然后试了很多次我去看自己上传的空间没有东西,并且我也不知道哪个代理可以监视文件是否已经开始上传或或者伤处啊能成功与否,求大神解救!!!
阿神2017-04-17 17:11:31
最后我每使用ASIHttpRequest,用NSURLSessionDataTask建立链接发请求了。
//上传文件方法
- (void)uploadFile
{
// 要上传的文件的文件名
NSString *folder = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *fileName = [folder stringByAppendingPathComponent:@"update测试/deer_head_reshaped-v3.6.0.STL"];
NSLog(@"Post filename is %@", fileName);
// 接收文件上传的地址
NSString *urlString = @"http://test.3dker.cn/api/upload/uploadp";
// 服务器端上传表单项的名称,一定与服务器端接收文件的名一致
NSString *uploadInputFieldName = @"file";
// 要传递的POST的参数,其中file对应上传文件的文件名
NSDictionary *params = @{
uploadInputFieldName: fileName,
@"key1": @"Value1" // 其他要POST传递的参数
};
/*********************以上按需要修改,下面的代码为固定代码,一般不需要修改*************************/
//分界线的标识符
NSString *TWITTERFON_FORM_BOUNDARY = @"AaB03x";
//根据url初始化request
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]
cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
timeoutInterval:10];
//设置登陆用户的X-Auth-Token
[request setValue:DownLoad_TOKEN forHTTPHeaderField:@"X-Auth-Token"];//若无则不需要
//分界线 --AaB03x
NSString *MPboundary=[[NSString alloc]initWithFormat:@"--%@",TWITTERFON_FORM_BOUNDARY];
//结束符 AaB03x--
NSString *endMPboundary=[[NSString alloc]initWithFormat:@"%@--",MPboundary];
//要上传的文件
NSString *imageFileName = [params objectForKey:uploadInputFieldName];
//得到图片的data
NSData* data = [NSData dataWithContentsOfFile:imageFileName];
//http body的字符串
NSMutableString *body=[[NSMutableString alloc]init];
//参数的集合的所有key的集合
NSArray *keys= [params allKeys];
//遍历keys
for(int i=0;i<[keys count];i++)
{
//得到当前key
NSString *key=[keys objectAtIndex:i];
//如果key不是pic,说明value是字符类型,比如name:Boris
if(![key isEqualToString:uploadInputFieldName])
{
//添加分界线,换行
[body appendFormat:@"%@\r\n",MPboundary];
//添加字段名称,换2行
[body appendFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",key];
//添加字段的值
[body appendFormat:@"%@\r\n",[params objectForKey:key]];
}
}
////添加分界线,换行
[body appendFormat:@"%@\r\n",MPboundary];
//声明文件字段,文件名为最后一个参数
[body appendFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\n", uploadInputFieldName, [[fileName componentsSeparatedByString:@"/"] lastObject]];
//声明上传文件的格式
[body appendFormat:@"Content-Type: stl\r\n\r\n"];
//声明结束符:--AaB03x--
NSString *end=[[NSString alloc]initWithFormat:@"\r\n%@",endMPboundary];
//声明myRequestData,用来放入http body
NSMutableData *myRequestData=[NSMutableData data];
//将body字符串转化为UTF8格式的二进制
[myRequestData appendData:[body dataUsingEncoding:NSUTF8StringEncoding]];
//将上传文件的data加入
[myRequestData appendData:data];
//加入结束符--AaB03x--
[myRequestData appendData:[end dataUsingEncoding:NSUTF8StringEncoding]];
//设置HTTPHeader中Content-Type的值
NSString *content=[[NSString alloc]initWithFormat:@"multipart/form-data; boundary=%@",TWITTERFON_FORM_BOUNDARY];
//设置HTTPHeader
[request setValue:content forHTTPHeaderField:@"Content-Type"];
//设置Content-Length
[request setValue:[NSString stringWithFormat:@"%ld", [myRequestData length]] forHTTPHeaderField:@"Content-Length"];
//设置http body
[request setHTTPBody:myRequestData];
//http method
[request setHTTPMethod:@"POST"];
/******************************以下代码为上传后,由服务器端返回的信息***********************************/
//建立连接,发送请求(ios9.0废弃)
// [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
//
// // 上传之后,接收返回的结果
//
// NSString *responseString = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
// NSLog(@"%@", responseString);
// }];
//构建NSURLSession
NSURLSession *session = [NSURLSession sharedSession];
//建立连接,发送请求
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
// 上传之后,接收返回的结果
NSString *responseString = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@", responseString);
if (error != nil) {
NSLog(@"上传失败");
}
}];
[task resume];
}
阿神2017-04-17 17:11:31
你是向上传一张图片的么? 为什么不去试试AFNetWorking? 以前培训学习的时候用过ASI上传不过好像没你这么复杂。下面是我上传头像外带参数的代码,你可以看看(AFNetwork写的。。不过应该差不多把。)
+(void)postAddActive:(NSString *)url : (NSMutableDictionary *) params: (NSData *) imageData: (void (^)(id t)) success{
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager.requestSerializer setTimeoutInterval:45];
[SVProgressHUD showWithStatus:@"请稍等上传中..."];
[manager POST:url parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
// NSData *data = UIImageJPEGRepresentation(imageTo, 0.7);
if(imageData !=nil){
[formData appendPartWithFileData:imageData name:[NSString stringWithFormat:@"file"] fileName:[NSString stringWithFormat:@"UploadeFile.png"] mimeType:@"image/png"];
}
} success:^(AFHTTPRequestOperation *operation,id responseObject) {
success(responseObject);
[SVProgressHUD showSuccessWithStatus:@"上传成功"];
[SVProgressHUD dismiss];
} failure:^(AFHTTPRequestOperation *operation,NSError *error) {
if (![operation isCancelled]) {
[SVProgressHUD showErrorWithStatus:@"上传失败"];
[SVProgressHUD dismiss];
}
}];
}