首页 \ 问答 \ AFNetworking 3.0用于上传图像错误的多部分表单数据(AFNetworking 3.0 Multipart form data for uploading image error)

AFNetworking 3.0用于上传图像错误的多部分表单数据(AFNetworking 3.0 Multipart form data for uploading image error)

我一直在尝试使用多部分表单数据afnetworking 3.0将图像上传到我的AWS服务器,但显然,我尝试上传的每个图像都在故障块中结束。 用objective-c编写的代码。

- (NSURLSessionUploadTask *)uploadImageTask:(NSMutableDictionary *)dictionary
{
    NSString *s3BucketUrl = [dictionary objectForKey:@"s3BucketUrl"];

    NSData *imageData = [dictionary objectForKey:@"imageData"];

    NSString *contentType = [dictionary objectForKey:@"contentType"];

    NSString *filename = [dictionary objectForKey:@"filename"];

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

       [formData appendPartWithFileData:imageData name:@"file" fileName:filename mimeType:contentType];
    } error:nil];

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

    NSURLSessionUploadTask *uploadTask = [[NSURLSessionUploadTask alloc] init];
    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

                      });
                  }
                  completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
                      if (!error) {

                          if (self.delegate != nil && [self.delegate respondsToSelector:@selector(onUploadImageTask:)])
                          {
                              [self.delegate onUploadImageTask:nil];
                          }

                      } else {

                          if (self.delegate != nil && [self.delegate respondsToSelector:@selector(onUploadImageTask:)])
                          {
                              [self.delegate onUploadImageTask:error];
                          }
                      }
                  }];

    [uploadTask resume];

    return uploadTask;
}

我得到的错误是

错误域= com.alamofire.error.serialization.response代码= -1011“请求失败:错误请求(400)”UserInfo = {NSUnderlyingError = 0x170248940 {Error Domain = com.alamofire.error.serialization.response Code = -1016“请求失败:不可接受的内容类型:application / xml“UserInfo = {com.alamofire.serialization.response.error.response = {URL: https://....s3.amazonaws.com/ } {status code:400 ,headers {Connection = close; “Content-Type”=“application / xml”; Date =“Tue,2016年12月20日01:53:47 GMT”; Server = AmazonS3; “转移编码”=身份; “x-amz-id-2”=“.....”; “x-amz-request-id”= ....; },

我尝试更改响应序列化程序的内容类型但仍然失败。


I've been trying to upload an image to my AWS server using multipart form data afnetworking 3.0 but apparently, every image I tried to upload ended up in the failure block. The codes in written in objective-c.

- (NSURLSessionUploadTask *)uploadImageTask:(NSMutableDictionary *)dictionary
{
    NSString *s3BucketUrl = [dictionary objectForKey:@"s3BucketUrl"];

    NSData *imageData = [dictionary objectForKey:@"imageData"];

    NSString *contentType = [dictionary objectForKey:@"contentType"];

    NSString *filename = [dictionary objectForKey:@"filename"];

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

       [formData appendPartWithFileData:imageData name:@"file" fileName:filename mimeType:contentType];
    } error:nil];

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

    NSURLSessionUploadTask *uploadTask = [[NSURLSessionUploadTask alloc] init];
    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

                      });
                  }
                  completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
                      if (!error) {

                          if (self.delegate != nil && [self.delegate respondsToSelector:@selector(onUploadImageTask:)])
                          {
                              [self.delegate onUploadImageTask:nil];
                          }

                      } else {

                          if (self.delegate != nil && [self.delegate respondsToSelector:@selector(onUploadImageTask:)])
                          {
                              [self.delegate onUploadImageTask:error];
                          }
                      }
                  }];

    [uploadTask resume];

    return uploadTask;
}

The error I'm getting is

Error Domain=com.alamofire.error.serialization.response Code=-1011 "Request failed: bad request (400)" UserInfo={NSUnderlyingError=0x170248940 {Error Domain=com.alamofire.error.serialization.response Code=-1016 "Request failed: unacceptable content-type: application/xml" UserInfo={com.alamofire.serialization.response.error.response= { URL: https://....s3.amazonaws.com/ } { status code: 400, headers { Connection = close; "Content-Type" = "application/xml"; Date = "Tue, 20 Dec 2016 01:53:47 GMT"; Server = AmazonS3; "Transfer-Encoding" = Identity; "x-amz-id-2" = "....."; "x-amz-request-id" = ....; } },

I tried changing the content-type for the response serializer and still fail.


原文:https://stackoverflow.com/questions/41233839
更新时间:2023-07-15 16:07

最满意答案

我来自azk核心团队,在这里我们通过简单地添加额外的对系统+ db并添加适当的设置来添加测试环境。

当您使用扩展测试系统时,它会更容易:

systems({
  example: {
    depends: ["postgres"],
    // ...
  },
  example-test: {
    extends: "example",
    depends: ["postgres-test"],
    scalable: { default: 0, limit: 1 },
    http: false,
    wait: false,
    envs: {
      // envs aren't extended by default. Add all required env vars from the original system here
      // ...
    },
  },
  postgres: {
    // ...
  },
  "postgres-test": {
    extends: "postgres",
    scalable: { default: 0, limit: 1 },
    envs: {
      // Once again, add the required env vars from postgres system here
      POSTGRES_USER: "azk",
      POSTGRES_PASS: "azk",
      POSTGRES_DB  : "#{manifest.dir}_test",
    },
  },
});

确保你的database.yml能够处理DATABASE_URL env var(我们强烈建议你使用这个: https//gist.github.com/gullitmiranda/62082f2e47c364ef9617

最后,要运行测试,只需执行:

$ azk start postgres-test
$ azk shell example-test -- bundle exec rake test

这应该足够了,但如果您有任何其他问题,请告诉我。


I'm from the azk core team and here we add a test environment by simply adding an extra pair system+db with proper settings.

It's even easier when you use extends for the test systems:

systems({
  example: {
    depends: ["postgres"],
    // ...
  },
  example-test: {
    extends: "example",
    depends: ["postgres-test"],
    scalable: { default: 0, limit: 1 },
    http: false,
    wait: false,
    envs: {
      // envs aren't extended by default. Add all required env vars from the original system here
      // ...
    },
  },
  postgres: {
    // ...
  },
  "postgres-test": {
    extends: "postgres",
    scalable: { default: 0, limit: 1 },
    envs: {
      // Once again, add the required env vars from postgres system here
      POSTGRES_USER: "azk",
      POSTGRES_PASS: "azk",
      POSTGRES_DB  : "#{manifest.dir}_test",
    },
  },
});

Make sure your database.yml is able to handle DATABASE_URL env var (we strongly recommend you use this one: https://gist.github.com/gullitmiranda/62082f2e47c364ef9617)

Finally, to run your tests, simply execute:

$ azk start postgres-test
$ azk shell example-test -- bundle exec rake test

This should be enough, but please let me know if you have any other issue.

相关问答

更多
  • 在puts ENV["RAILS_ENV"] ,它表明我的测试在test environment直接运行。 但是正在运行的本地工头服务器正在从development environment获取数据。 通过手动指定服务器应在test environment运行,测试还使用来自test environment数据。 非常感谢@AndyWaite。 On puts ENV["RAILS_ENV"], it shows that my test was running straight on test enviro ...
  • 添加以下注释就可以了: @TransactionConfiguration(transactionManager="transactionManager", defaultRollback=false) @Transactional 以下是最终的完整配置: @TransactionConfiguration(transactionManager="transactionManager", defaultRollback=false) @Transactional @RunWith(SpringJUnit4 ...
  • 也许你可以使用类似Moq的方式来模拟更新数据库(或DAL层)的服务,避免调用数据库并使用模拟的验证方法检查对数据库的调用将被执行。 在我们的项目中,我们使用wcf的这个库获得了很好的结果。 I decided to go with an implementation that is application specific. Basically creating a test database, and having our application hit the test database based o ...
  • 确保在运行测试之前禁用python manage.py runserver或访问postgresql的任何其他进程(例如pgadmin3或phppgadmin)。 换句话说,确保已经杀死了应用程序的运行postgresql连接 。 您还可以确定应用程序通过哪些打开的连接到postgresql数据库 psql -U postgres postgres=# SELECT * FROM pg_stat_activity; 如果你想具体,你可以这样做: - postgres=# SELECT * FROM pg ...
  • 我来自azk核心团队,在这里我们通过简单地添加额外的对系统+ db并添加适当的设置来添加测试环境。 当您使用扩展测试系统时,它会更容易: systems({ example: { depends: ["postgres"], // ... }, example-test: { extends: "example", depends: ["postgres-test"], scalable: { default: 0, limit: 1 }, htt ...
  • 在我看来,单元测试应尽可能与其他单元测试隔离。 否则,更改测试运行的顺序可能会导致先前通过的测试失败(反之亦然)。 因此,我建议您在每次测试之前继续设置和拆除数据库。 根据我的经验,您通常只需要为每个测试设置一些项目 - 并且相同的设置代码通常可以由多个测试共享(例如,通过将该代码放在基类的setUp方法中)。 当然,有一些参数可以提前进行设置(对于多个测试) - 例如在setUpClass方法中甚至是setUpModule ...主要的论点是它可能在运行测试时节省一点时间 - 这绝不是对我来说一直是一个问 ...
  • 这来自开发人员的观点,而不是测试人员,所以它可能适用也可能不适用。 我不能代表整个组织,但在我们的项目中,我们花了一些时间创建“真实世界”的数据,我们使用SQL脚本加载到测试数据库中。 这些数据是来自生产环境的实际数据和定制的数据的组合,用于表示我们产品中的特定“问题情况”。 这些脚本作为构建我们软件的一部分自动运行,并由单元测试框架驱动的自动化集成测试使用。 这些测试将测试通过各种可用接口查找,创建,编辑和删除数据。 在这样的构建和测试运行期间,测试数据库被重置并在许多情况下重新加载数据。 这样做是为了消 ...
  • 您需要将Selenium指向使用测试数据库的站点。 Selenium与您的rails交谈,而不是数据库。 因此,您需要将Selenium指向一个Web应用程序,其配置指向您的测试数据库,而不是dev db。 希望有所帮助。 You need to point Selenium to a site that uses the test databases. Selenium talks to your rails, not the database. So, you need to point Seleniu ...
  • 我只是在PR中添加了图像存储库中的指令: https://github.com/azukiapp/docker-postgres/pull/3 请参阅部分: 迁移现有的PostgreSQL服务器 I just make a PR adding the instructions in the repository of the image: https://github.com/azukiapp/docker-postgres/pull/3 see section: Migrating an existing ...
  • 尝试RACK_ENV而不是RAILS_ENV : $ rake db:create RACK_ENV=test 要么: $ RACK_ENV=test rake db:create Try RACK_ENV instead of RAILS_ENV: $ rake db:create RACK_ENV=test Or: $ RACK_ENV=test rake db:create

相关文章

更多

最新问答

更多
  • 获取MVC 4使用的DisplayMode后缀(Get the DisplayMode Suffix being used by MVC 4)
  • 如何通过引用返回对象?(How is returning an object by reference possible?)
  • 矩阵如何存储在内存中?(How are matrices stored in memory?)
  • 每个请求的Java新会话?(Java New Session For Each Request?)
  • css:浮动div中重叠的标题h1(css: overlapping headlines h1 in floated divs)
  • 无论图像如何,Caffe预测同一类(Caffe predicts same class regardless of image)
  • xcode语法颜色编码解释?(xcode syntax color coding explained?)
  • 在Access 2010 Runtime中使用Office 2000校对工具(Use Office 2000 proofing tools in Access 2010 Runtime)
  • 从单独的Web主机将图像传输到服务器上(Getting images onto server from separate web host)
  • 从旧版本复制文件并保留它们(旧/新版本)(Copy a file from old revision and keep both of them (old / new revision))
  • 西安哪有PLC可控制编程的培训
  • 在Entity Framework中选择基类(Select base class in Entity Framework)
  • 在Android中出现错误“数据集和渲染器应该不为null,并且应该具有相同数量的系列”(Error “Dataset and renderer should be not null and should have the same number of series” in Android)
  • 电脑二级VF有什么用
  • Datamapper Ruby如何添加Hook方法(Datamapper Ruby How to add Hook Method)
  • 金华英语角.
  • 手机软件如何制作
  • 用于Android webview中图像保存的上下文菜单(Context Menu for Image Saving in an Android webview)
  • 注意:未定义的偏移量:PHP(Notice: Undefined offset: PHP)
  • 如何读R中的大数据集[复制](How to read large dataset in R [duplicate])
  • Unity 5 Heighmap与地形宽度/地形长度的分辨率关系?(Unity 5 Heighmap Resolution relationship to terrain width / terrain length?)
  • 如何通知PipedOutputStream线程写入最后一个字节的PipedInputStream线程?(How to notify PipedInputStream thread that PipedOutputStream thread has written last byte?)
  • python的访问器方法有哪些
  • DeviceNetworkInformation:哪个是哪个?(DeviceNetworkInformation: Which is which?)
  • 在Ruby中对组合进行排序(Sorting a combination in Ruby)
  • 网站开发的流程?
  • 使用Zend Framework 2中的JOIN sql检索数据(Retrieve data using JOIN sql in Zend Framework 2)
  • 条带格式类型格式模式编号无法正常工作(Stripes format type format pattern number not working properly)
  • 透明度错误IE11(Transparency bug IE11)
  • linux的基本操作命令。。。