ios - 使用 AFNetworking 3.0 上传图片

标签 ios objective-c iphone

我尝试使用 AFNetworking3.0 上传图像。 我试图找到如何从所有 stackoverflow 和教程中上传图像,但所有这些都与 AFNetworking2.0 及以下版本相关。 重点是我要将图像上传到网站。

图片上传后,网站上应该存在图片 url。

请看下面的代码。

AFHTTPRequestOperationManager *requestManager;

[requestManager POST:KAPIUploadOutfit parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) 
{
        [formData appendPartWithFileURL:fileURL name:@"photo_url" fileName:filename mimeType:@"image/png" error:nil];
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        successCB(responseObject);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        errorCB(CONNECTION_ERROR);
    }];

我不确定参数是什么。 请告诉我该怎么做。

最佳答案

NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"http://example.com/upload" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
    [formData appendPartWithFileURL:[NSURL fileURLWithPath:@"file://path/to/image.jpg"] name:@"file" fileName:@"filename.jpg" mimeType:@"image/jpeg" error:nil];
} error:nil];

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

NSURLSessionUploadTask *uploadTask;
uploadTask = [manager
          uploadTaskWithStreamedRequest:request
          progress:^(NSProgress * _Nonnull uploadProgress) {
              // This is not called back on the main queue.
              // You are responsible for dispatching to the main queue for UI updates
              dispatch_async(dispatch_get_main_queue(), ^{
                  //Update the progress view
                  [progressView setProgress:uploadProgress.fractionCompleted];
              });
          }
          completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
              if (error) {
                  NSLog(@"Error: %@", error);
              } else {
                  NSLog(@"%@ %@", response, responseObject);
              }
          }];

[uploadTask resume];

在此代码中 http://example.com/upload是要上传图片的 api,file://path/to/image.jpg 是您的本 map 片路径。

关于ios - 使用 AFNetworking 3.0 上传图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35947930/

相关文章:

ios - 避免致命车祸

iOS:模式转换到黑屏?

ios - 8 位颜色到 UIColor

ios - (Cocoa 错误 3840。)“(字符 0 周围的值无效。)AFNetworking

ios - 用另一个 CALayer 屏蔽 CALayer

objective-c - 如何使用代码读取协同设计信息

ios - 返回数组中最小的数字

objective-c - UIBezierPath 绘制的 View 的模糊屏幕截图

javascript - iOS:禁用弹跳滚动但允许正常滚动

使用 Phonegap 打开 Iphone 联系人应用程序