@第一种:我的


[objc]​view plain​​​​copy​​​​​​​​​


  1. #pragma mark - AFNetworking上传文件
  2. - (void)didClickUploadButtonAction{

  3. NSString *fileName = @"hmt";
  4. // 确定需要上传的文件(假设选择本地的文件)
  5. NSURL *filePath = [[NSBundle mainBundle] URLForResource:fileName withExtension:@"png"];
  6. NSDictionary *parameters = @{@"name":@"额外的请求参数"};
  7. AFHTTPRequestOperationManager *requestManager = [AFHTTPRequestOperationManager manager];
  8. [requestManager POST:@"http://192.168.10.18:8080/AFNetworkingServer/upload" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {

  9. /**
  10. * appendPartWithFileURL // 指定上传的文件
  11. * name // 指定在服务器中获取对应文件或文本时的key
  12. * fileName // 指定上传文件的原始文件名
  13. * mimeType // 指定商家文件的MIME类型
  14. */
  15. [formData appendPartWithFileURL:filePath name:@"file" fileName:[NSString stringWithFormat:@"%@.png",fileName] mimeType:@"image/png" error:nil];

  16. } success:^(AFHTTPRequestOperation *operation, id responseObject) {

  17. [[[UIAlertView alloc] initWithTitle:@"上传结果" message:[[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding] delegate:self cancelButtonTitle:@"" otherButtonTitles:nil] show];

  18. } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

  19. NSLog(@"获取服务器响应出错");

  20. }];

  21. }


@第二种:(朋友的)



[objc]​view plain​​​​copy​​​​​​​​​


  1. NSData *imageData = UIImagePNGRepresentation(image);

  2. //转码成UTF-8 否则可能会出现错误


  3. NSString *URLTmp = [NSString stringWithFormat:@"%@%@",CGBaseURL,path];

  4. NSString *URLTmps = [URLTmp stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

  5. URLTmp = URLTmps;

  6. NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:URLTmp parameters:body constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {

  7. [formData appendPartWithFileData:imageData name:@"headerImg" fileName:@"123.png" mimeType:@"image/png"];

  8. } error:nil];



  9. AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];

  10. NSProgress *progress = nil;


  11. manager.responseSerializer = [AFHTTPResponseSerializer serializer];


  12. NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:&progress completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {

  13. if (error) {

  14. NSLog(@"Error: %@", error);

  15. } else {

  16. block(responseObject);
  17. }

  18. }];


  19. [uploadTask resume];