AFNetworking框架_上传文件或图片到服务器
文中的 XXXXXXXXXX更具你自己的参数填写
- (void)uploadImageWithImage:(NSString *)imagePath
{
//上传其他所需参数
NSString *userId=XXXXXXXXXXX;
NSString *token=XXXXXXXXXXX;
//上传请求POST
AFHTTPClient *client=[AFHTTPClient clientWithBaseURL:[NSURL URLWithString:@""]];
NSString *urlString=[NSString stringWithFormat:@"上传服务器地址];
NSDictionary *dic=[[NSDictionary alloc] initWithObjectsAndKeys:userId,@"XXXXXX",token,@"XXXXXX", nil];
NSURLRequest *request = [client multipartFormRequestWithMethod:@"POST" path:urlString parameters:dic constructingBodyWithBlock:^(id formData) {
//得到需要上传的数据
NSData *data=[NSData dataWithContentsOfFile:imagePath];
//上传时使用当前的系统事件作为文件名
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"yyyyMMddHHmmss";
NSString *str = [formatter stringFromDate:[NSDate date]];
NSString *fileName = [NSString stringWithFormat:@"%@.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 = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"上传完成");
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"上传失败->%@", error);
}];
//执行
[client.operationQueue addOperation:op];
}
上一篇: mysql电子商城建表代码参考
下一篇: ps怎么画一头黑色的小猪?