首页 \ 问答 \ 使用HTTPClient使用RestKit 0.20上传文件(File uploads with RestKit 0.20 using HTTPClient)

使用HTTPClient使用RestKit 0.20上传文件(File uploads with RestKit 0.20 using HTTPClient)

我目前正在使用以下代码发布到我的服务器:

[[[RKObjectManager sharedManager] HTTPClient] postPath:[NSString stringWithFormat:@"%@%@", baseURL, @"/api/v2/track-it/rack/individual"]
                                                    parameters:params
                                                       success:^(AFHTTPRequestOperation *operation, id responseObject) {
                                                           // handle success                                                               
                                                           if([[responseObject[@"result"] lowercaseString] isEqualToString:@"success"]){
                                                               // Entry was added
                                                               UIViewController *otherVC = [[UIStoryboard storyboardWithName:@"App" bundle:nil] instantiateViewControllerWithIdentifier:@"Dashboard"];
                                                               [self presentViewController:otherVC animated:YES completion:nil];

                                                               [self alertWithTitle:@"Track It Entry" message:@"The entry was uploaded successfully"];
                                                           } else {
                                                               // Couldn't add entry
                                                               [self alertWithTitle:@"Track It Entry" message:@"An error occured. Saving entry to upload later."];
                                                           }
                                                       }
                                                       failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                                                           // response code is in operation.response.statusCode
                                                           NSLog(@"ERROR");
                                                       }];

params是值的NSDictionary

如何上传文件?
我在任何没有使用托管对象的地方都找不到任何示例。


I am currently using the following code to post to my server:

[[[RKObjectManager sharedManager] HTTPClient] postPath:[NSString stringWithFormat:@"%@%@", baseURL, @"/api/v2/track-it/rack/individual"]
                                                    parameters:params
                                                       success:^(AFHTTPRequestOperation *operation, id responseObject) {
                                                           // handle success                                                               
                                                           if([[responseObject[@"result"] lowercaseString] isEqualToString:@"success"]){
                                                               // Entry was added
                                                               UIViewController *otherVC = [[UIStoryboard storyboardWithName:@"App" bundle:nil] instantiateViewControllerWithIdentifier:@"Dashboard"];
                                                               [self presentViewController:otherVC animated:YES completion:nil];

                                                               [self alertWithTitle:@"Track It Entry" message:@"The entry was uploaded successfully"];
                                                           } else {
                                                               // Couldn't add entry
                                                               [self alertWithTitle:@"Track It Entry" message:@"An error occured. Saving entry to upload later."];
                                                           }
                                                       }
                                                       failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                                                           // response code is in operation.response.statusCode
                                                           NSLog(@"ERROR");
                                                       }];

params is an NSDictionary of values.

How can I upload files with this?
I can't find any examples anywhere that aren't using a Managed Object.


原文:https://stackoverflow.com/questions/31865535
更新时间:2022-03-10 06:03

最满意答案

您需要自定义模型联编程序才能正常工作。 这是您可以开始使用的简化版本:

public class CsvIntModelBinder : IModelBinder
{
    public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
    {
        var key = bindingContext.ModelName;
        var valueProviderResult = bindingContext.ValueProvider.GetValue(key);
        if (valueProviderResult == null)
        {
            return false;
        }

        var attemptedValue = valueProviderResult.AttemptedValue;
        if (attemptedValue != null)
        {
            var list = attemptedValue.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries).
                       Select(v => int.Parse(v.Trim())).ToList();

            bindingContext.Model = list;
        }
        else
        {
            bindingContext.Model = new List<int>();
        }
        return true;
    }
}

并以这种方式使用它(从路由中删除{ids} ):

[HttpGet]
[Route("api/NewHotelData")]
public HttpResponseMessage Get([ModelBinder(typeof(CsvIntModelBinder))] List<int> ids)

如果您想保留{ids}的路线,您应该将客户端请求更改为:

api/NewHotelData/1,2,3,4

另一个选项( 没有自定义模型绑定)正在将获取请求更改为:

?ids=1&ids=2&ids=3

You'll need custom model binder to get this working. Here's simplified version you can start work with:

public class CsvIntModelBinder : IModelBinder
{
    public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
    {
        var key = bindingContext.ModelName;
        var valueProviderResult = bindingContext.ValueProvider.GetValue(key);
        if (valueProviderResult == null)
        {
            return false;
        }

        var attemptedValue = valueProviderResult.AttemptedValue;
        if (attemptedValue != null)
        {
            var list = attemptedValue.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries).
                       Select(v => int.Parse(v.Trim())).ToList();

            bindingContext.Model = list;
        }
        else
        {
            bindingContext.Model = new List<int>();
        }
        return true;
    }
}

And use it this way (remove {ids} from route):

[HttpGet]
[Route("api/NewHotelData")]
public HttpResponseMessage Get([ModelBinder(typeof(CsvIntModelBinder))] List<int> ids)

If you want to keep {ids} in route, you should change client request to:

api/NewHotelData/1,2,3,4

Another option (without custom model binder) is changing get request to:

?ids=1&ids=2&ids=3

相关问答

更多
  • 您可以使用库Apache HTTP组件 doGet()简短示例(我没有编译它): import org.apache.http.*; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http. ...
  • 作为快速修复,将Play更改为PlayAPI.Models.Product上的Int64。 public Int64 Stock { get; set; } 我的理解是,用于修补现有对象的Delta对象不使用JSON.net进行转换,并在分析JSON时静默抛出无效的强制转换异常,然后与数据库中的现有对象进行比较。 您可以在此处阅读有关该错误的更多信息: http : //aspnetwebstack.codeplex.com/workitem/777 As a quick fix, Change the ...
  • 好。 我找到了解决方案。 当前的API服务代码保持不变。 客户端代码将在字符串中包含请求参数,并将其作为参数传递给服务。 完成。 自动模型绑定将触发 OK. I found a solution to this. Current API Service code remains same. client code will have request params in a string and pass this as a param to the Service. Done. Auto model bin ...
  • 只是不要“屈服”“获取”返回的未来。 然后你的协同将立即继续循环,并且当fetch在后台完成时执行回调。 此外,永远不要在Tornado应用程序中调用“sleep”: http://www.tornadoweb.org/en/stable/faq.html#why-isn-t-this-example-with-time-sleep-running-in-parallel 如果这样做,所有处理都会停止,并且“fetch”将一直挂起,直到睡眠完成。 代替: yield gen.sleep(delay) Si ...
  • 你可以使用这个: 在Json中请求正文 [{id:1, nombre:"kres"}, {id:2, nombre:"cruz"}] Api Rest .net C# public string myFunction(IEnumerable myObj) { //... return "response"; } You can use this : Request body in Json [{id:1, nombre:"kres"}, {id:2, n ...
  • 使用Newtonsoft.Json库来序列化您的凭证对象。 你的Consume功能就是这样 private static string Consume(string endpoint, string user, string password) { var client = new HttpClient(); client.BaseAddress = new Uri(endpoint); client.DefaultRequestHeaders.Accept.Clear(); ...
  • 您需要自定义模型联编程序才能正常工作。 这是您可以开始使用的简化版本: public class CsvIntModelBinder : IModelBinder { public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext) { var key = bindingContext.ModelName; var valueProviderRe ...
  • HttpClient.PutAsync是一个异步API,它返回一个Task ,它表示将来需要await 。 你将HttpClient包装在using语句中,这意味着在你触发异步PUT之后,你正在处理客户端,这会导致请求和处理对象的竞争条件,这可能是你'的原因。没有看到请求火了。 你有两个选择。 使方法成为async Task并在其中await : public async Task UpdateWerknemerCompetentieDetailAsync( ...
  • 你不需要做任何事情,这将开箱即用。 如果您发布您提供的确切对象: { "ID" : 3 , "SelectedChoiceIDs" : [ 3,4,5,6 ] } 使用Content-Type: application/json ,默认的模型绑定器将自动拾取它。 public class PostData { public int ID { get; set; } public int[] SelectedChoiceIDs { get; set; } } public void ...
  • 您正在使用的params选项将项添加到查询字符串,对于您可能希望使用数据选项的帖子,请尝试将代码更改为: $scope.UpdateTrans=function(){ alert("21312"); $http({method:"post", url:'http://localhost:18678/api/Transaction', data:$scope.AddTrn } ...

相关文章

更多

最新问答

更多
  • python的访问器方法有哪些
  • 使用Zend Framework 2中的JOIN sql检索数据(Retrieve data using JOIN sql in Zend Framework 2)
  • 透明度错误IE11(Transparency bug IE11)
  • linux的基本操作命令。。。
  • 响应navi重叠h1和nav上的h1链接不起作用(Responsive navi overlaps h1 and navi links on h1 isn't working)
  • 在C中读取文件:“r”和“a +”标志的不同行为(Reading a File in C: different behavior for “r” and “a+” flags)
  • NFC提供什么样的带宽?(What Kind of Bandwidth does NFC Provide?)
  • 元素上的盒子阴影行为(box-shadow behaviour on elements)
  • Laravel检查是否存在记录(Laravel Checking If a Record Exists)
  • 设置base64图像的大小javascript - angularjs(set size of a base64 image javascript - angularjs)
  • 想学Linux 运维 深圳有哪个培训机构好一点
  • 为什么有时不需要在lambda中捕获一个常量变量?(Why is a const variable sometimes not required to be captured in a lambda?)
  • 在Framework 3.5中使用服务器标签<%=%>设置Visible属性(Set Visible property with server tag <%= %> in Framework 3.5)
  • AdoNetAppender中的log4net连接类型无效(log4net connection type invalid in AdoNetAppender)
  • 错误:发送后无法设置标题。(Error: Can't set headers after they are sent. authentication system)
  • 等待EC2实例重启(Wait for an EC2 instance to reboot)
  • 如何在红宝石中使用正则表达式?(How to do this in regex in ruby?)
  • 使用鼠标在OpenGL GLUT中绘制多边形(Draw a polygon in OpenGL GLUT with mouse)
  • 江民杀毒软件的KSysnon.sys模块是什么东西?
  • 处理器在传递到add_xpath()或add_value()时调用了什么顺序?(What order are processors called when passed into add_xpath() or add_value()?)
  • sp_updatestats是否导致SQL Server 2005中无法访问表?(Does sp_updatestats cause tables to be inaccessible in SQL Server 2005?)
  • 如何创建一个可以与持续运行的服务交互的CLI,类似于MySQL的shell?(How to create a CLI that can interact with a continuously running service, similar to MySQL's shell?)
  • AESGCM解密失败的MAC(AESGCM decryption failing with MAC)
  • SQL查询,其中字段不包含$ x(SQL Query Where Field DOES NOT Contain $x)
  • PerSession与PerCall(PerSession vs. PerCall)
  • C#:有两个构造函数的对象:如何限制哪些属性设置在一起?(C#: Object having two constructors: how to limit which properties are set together?)
  • 平衡一个精灵(Balancing a sprite)
  • n2cms Asp.net在“文件”菜单上给出错误(文件管理器)(n2cms Asp.net give error on Files menu (File Manager))
  • Zurb Foundation 4 - 嵌套网格对齐问题(Zurb Foundation 4 - Nested grid alignment issues)
  • 湖北京山哪里有修平板计算机的