首页 > 代码库 > AFNetworking框架_上传文件或图片到服务器
AFNetworking框架_上传文件或图片到服务器
文中的 XXXXXXXXXX更具你自己的参数填写
- (void)uploadImageWithImage:(NSString *)imagePath
{
//上传其他所需参数
NSString *userId=XXXXXXXXXXX;
NSString *token=XXXXXXXXXXX;
//上传请求POST
AFHTTPClient *client=[AFHTTPClientclientWithBaseURL:[NSURLURLWithString:@""]];
NSString *urlString=[NSStringstringWithFormat:@"上传服务器地址];
NSDictionary *dic=[[NSDictionaryalloc] initWithObjectsAndKeys:userId,@"XXXXXX",token,@"XXXXXX",nil];
NSURLRequest *request = [clientmultipartFormRequestWithMethod:@"POST"path:urlString parameters:dicconstructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
//得到需要上传的数据
NSData *data=http://www.mamicode.com/[NSDatadataWithContentsOfFile:imagePath];
//上传时使用当前的系统事件作为文件名
NSDateFormatter *formatter = [[NSDateFormatteralloc] init];
formatter.dateFormat =@"yyyyMMddHHmmss";
NSString *str = [formatter stringFromDate:[NSDate date]];
NSString *fileName = [NSStringstringWithFormat:@"%@.jpg", str];
/*
此方法参数
1. 要上传的[二进制数据]
2. 对应网站上[upload.php中]处理文件的[字段"file"]
3. 要保存在服务器上的[文件名]
4. 上传文件的[mimeType]
*/
//服务器上传文件的字段和类型
[formData appendPartWithFileData:data name:@"XXXXX"fileName:fileName mimeType:@"image/jpg/file"];
}];
// 3. operation包装的urlconnetion
AFHTTPRequestOperation *op = [[AFHTTPRequestOperationalloc] initWithRequest:request];
[opsetCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation,id responseObject) {
NSLog(@"上传完成");
}failure:^(AFHTTPRequestOperation *operation,NSError *error) {
NSLog(@"上传失败->%@", error);
}];
//执行
[client.operationQueueaddOperation:op];
}
AFNetworking框架_上传文件或图片到服务器