首页 \ 问答 \ 使用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 } ...

相关文章

更多

最新问答

更多
  • 如何检索Ember.js模型的所有属性(How to retrieve all properties of an Ember.js model)
  • maven中snapshot快照库和release发布库的区别和作用
  • arraylist中的搜索元素(Search element in arraylist)
  • 从mysli_fetch_array中获取选定的值并输出(Get selected value from mysli_fetch_array and output)
  • Windows Phone上的可用共享扩展(Available Share Extensions on Windows Phone)
  • 如何在命令提示符下将日期设置为文件名(How to set file name as date in command prompt)
  • 如何在Laravel 5.2中使用paginate与关系?(How to use paginate with relationships in Laravel 5.2?)
  • 从iframe访问父页面的id元素(accessing id element of parent page from iframe)
  • linux的常用命令干什么用的
  • Feign Client + Eureka POST请求正文(Feign Client + Eureka POST request body)
  • 怎么删除禁用RHEL/CentOS 7上不需要的服务
  • 为什么Gradle运行测试两次?(Why does Gradle run tests twice?)
  • 由于有四个新控制器,Auth刀片是否有任何变化?(Are there any changes in Auth blades due to four new controllers?)
  • 如何交换返回集中的行?(How to swap rows in a return set?)
  • 在android中的活动之间切换?(Switching between activities in android?)
  • Perforce:如何从Depot到Workspace丢失文件?(Perforce: how to get missing file from Depot to Workspace?)
  • Webform页面避免运行服务器(Webform page avoiding runat server)
  • 在ios 7中的UITableView部分周围绘制边界线(draw borderline around UITableView section in ios 7)
  • 内存布局破解(memory layout hack)
  • 使用Boost.Spirit Qi和Lex时的空白队长(Whitespace skipper when using Boost.Spirit Qi and Lex)
  • 我们可以有一个调度程序,你可以异步添加东西,但会同步按顺序执行吗?(Can we have a dispatcher that you can add things todo asynchronously but will be executed in that order synchronously?)
  • “FROM a,b”和“FROM a FULL OUTER JOIN b”之间有什么区别?(What is the difference between “FROM a, b” and “FROM a FULL OUTER JOIN b”?)
  • Java中的不可变类(Immutable class in Java)
  • bat批处理文件结果导出到txt
  • WordPress发布查询(WordPress post query)
  • 如何在关系数据库中存储与IPv6兼容的地址(How to store IPv6-compatible address in a relational database)
  • 是否可以检查对象值的条件并返回密钥?(Is it possible to check the condition of a value of an object and JUST return the key?)
  • 德州新起点计算机培训学校主要课程有什么?
  • GEP分段错误LLVM C ++ API(GEP segmentation fault LLVM C++ API)
  • “latin1_german1_ci”整理来自哪里?(Where is “latin1_german1_ci” collation coming from?)