使用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

相关问答

更多

从Java Servlet向Web API发送get请求(To send get request to Web API from Java Servlet)

您可以使用库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....

Web API 2不处理整数的PATCH请求(Web API 2 does not process PATCH requests for Integers)

作为快速修复,将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...

从客户端调用Web API(Calling Web API from client)

好。 我找到了解决方案。 当前的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 mode...

发送多个Web请求(Send multiple Web requests)

只是不要“屈服”“获取”返回的未来。 然后你的协同将立即继续循环,并且当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...

发送对象列表到Web API(Sending list of objects to Web API)

你可以使用这个: 在Json中请求正文 [{id:1, nombre:"kres"}, {id:2, nombre:"cruz"}] Api Rest .net C# public string myFunction(IEnumerable<EntitySomething> myObj) { //... return "response"; } You can use this : Request body in Json [{id:1, nombre:"kres"}, {id...

如何在正文请求中将参数发送到Web API?(How to send parameters to web API in the body request?)

使用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()...

如何向Web api发送整数列表2获取请求?(How to send a list of integers to web api 2 get request?)

您需要自定义模型联编程序才能正常工作。 这是您可以开始使用的简化版本: public class CsvIntModelBinder : IModelBinder { public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext) { var key = bindingContext.ModelName; var valueProvi...

PutAsync不向web api发送请求,但fiddler工作正常(PutAsync doesn't send request to web api, but fiddler works fine)

HttpClient.PutAsync是一个异步API,它返回一个Task<HttpResponseMessage> ,它表示将来需要await 。 你将HttpClient包装在using语句中,这意味着在你触发异步PUT之后,你正在处理客户端,这会导致请求和处理对象的竞争条件,这可能是你'的原因。没有看到请求火了。 你有两个选择。 使方法成为async Task并在其中await : public async Task UpdateWerknemerCompetentieDetailAsync...

将整数数组发布到asp.net web api(Posting array of integers to asp.net web api)

你不需要做任何事情,这将开箱即用。 如果您发布您提供的确切对象: { "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...

如何通过Angular向ASP.net web API发送帖子请求(How to send post request through Angular to ASP.net web API)

您正在使用的params选项将项添加到查询字符串,对于您可能希望使用数据选项的帖子,请尝试将代码更改为: $scope.UpdateTrans=function(){ alert("21312"); $http({method:"post", url:'http://localhost:18678/api/Transaction', data:$scope.AddTrn } ...

相关文章

更多

httpclient get请求

httpclient get进行get请求步骤: 1、创建Httpclient对象 HttpCli ...

HttpClient 上传文件

我们使用MultipartEntityBuilder创建一个HttpEntity。 当创建构建器时,添 ...

HttpClient CacheConfig缓存处理示例

是如何设置基本缓存HttpClient的简单示例。 按照配置,它将存储最多3000个缓存对象,其中每个 ...

HttpClient DELETE请求示例

本教程演示如何使用Apache HttpClient 4.5创建Http DELETE请求。 HTTP ...

Httpclient整合Spring教程

Httpclient和Spring的整合就是把直接new对象的方式改为spring配置即可 1、首先 ...

HttpClient 重定向处理

HttpClient自动处理所有类型的重定向,除了HTTP规范明确禁止的那些重定向需要用户干预。 请参 ...

HttpClient PUT请求示例

本教程演示如何使用Apache HttpClient 4.5发出Http PUT请求。 HTTP PU ...

httpclient依懒包官网下载及httpclient maven依懒包获取

httpclient官网 http://hc.apache.org/ httpclient下载地址 h ...

HttpClient 请求添加Header头部信息

HTTP消息可以包含许多描述消息属性的标头,例如内容长度,内容类型,授权等。 HttpClient提供 ...

Hadoop0.20+ custom MultipleOutputFormat

Hadoop0.20.2中无法使用MultipleOutputFormat,多文件输出这个方法。尽管0 ...

最新问答

更多

获取MVC 4使用的DisplayMode后缀(Get the DisplayMode Suffix being used by MVC 4)

我用Google搜索了一个解决方案。 “EnumDisplayModeProvider”是我自己设置网站的各种模式的枚举。 public EnumDisplayModeProvider GetDisplayModeId() { foreach (var mode in DisplayModeProvider.Instance.Modes) if (mode.CanHandleContext(HttpContext)) {

如何通过引用返回对象?(How is returning an object by reference possible?)

这相对简单:在类的构造函数中,您可以分配内存,例如使用new 。 如果你制作一个对象的副本,你不是每次都分配新的内存,而是只复制指向原始内存块的指针,同时递增一个也存储在内存中的引用计数器,使得每个副本都是对象可以访问它。 如果引用计数降至零,则销毁对象将减少引用计数并仅释放分配的内存。 您只需要一个自定义复制构造函数和赋值运算符。 这基本上是共享指针的工作方式。 This is relatively easy: In the class' constructor, you allocate m

矩阵如何存储在内存中?(How are matrices stored in memory?)

正如它在“熵编码”中所说的那样,使用Z字形图案,与RLE一起使用,在许多情况下,RLE已经减小了尺寸。 但是,据我所知,DCT本身并没有给出稀疏矩阵。 但它通常会增强矩阵的熵。 这是compressen变得有损的点:输入矩阵用DCT传输,然后量化量化然后使用霍夫曼编码。 As it says in "Entropy coding" a zig-zag pattern is used, together with RLE which will already reduce size for man

每个请求的Java新会话?(Java New Session For Each Request?)

你是如何进行重定向的? 您是否事先调用了HttpServletResponse.encodeRedirectURL()? 在这里阅读javadoc 您可以使用它像response.sendRedirect(response.encodeRedirectURL(path)); The issue was with the path in the JSESSIONID cookie. I still can't figure out why it was being set to the tomca

css:浮动div中重叠的标题h1(css: overlapping headlines h1 in floated divs)

我认为word-break ,如果你想在一个单词中打破行,你可以指定它,这样做可以解决问题: .column { word-break:break-all; } jsFiddle演示。 您可以在此处阅读有关word-break属性的更多信息。 I think word-break, with which you can specify if you want to break line within a word, will do the trick: .column { word-break

无论图像如何,Caffe预测同一类(Caffe predicts same class regardless of image)

我认为您忘记在分类时间内缩放输入图像,如train_test.prototxt文件的第11行所示。 您可能应该在C ++代码中的某个位置乘以该因子,或者使用Caffe图层来缩放输入(请查看ELTWISE或POWER图层)。 编辑: 在评论中进行了一次对话之后,结果发现在classification.cpp文件中错误地删除了图像均值,而在原始训练/测试管道中没有减去图像均值。 I think you have forgotten to scale the input image during cl

xcode语法颜色编码解释?(xcode syntax color coding explained?)

转到: Xcode => Preferences => Fonts & Colors 您将看到每个语法高亮颜色旁边都有一个简短的解释。 Go to: Xcode => Preferences => Fonts & Colors You'll see that each syntax highlighting colour has a brief explanation next to it.

在Access 2010 Runtime中使用Office 2000校对工具(Use Office 2000 proofing tools in Access 2010 Runtime)

你考虑过第三方拼写检查吗? 您可以将在C#中开发的自定义WinForms控件插入访问数据库吗? VB6控件怎么样? 如果你能找到一个使用第三方库进行拼写检查的控件,那可能会有效。 Have you considered a third party spell checker? Can you insert a custom WinForms controls developed in C# into an access database? What about a VB6 control? If

从单独的Web主机将图像传输到服务器上(Getting images onto server from separate web host)

我有同样的问题,因为我在远程服务器上有两个图像,我需要在每天的预定义时间复制到我的本地服务器,这是我能够提出的代码... try { if(@copy('url/to/source/image.ext', 'local/absolute/path/on/server/' . date("d-m-Y") . ".gif")) { } else { $errors = error_get_last(); throw new Exception($err

从旧版本复制文件并保留它们(旧/新版本)(Copy a file from old revision and keep both of them (old / new revision))

我不确定我完全明白你在说什么。 你能编辑你的帖子并包含你正在做的Subversion命令/操作的特定顺序吗? 最好使用命令行svn客户端,以便容易为其他人重现问题。 如果您只是想获取文件的旧副本(即使该文件不再存在),您可以使用如下命令: svn copy ${repo}/trunk/moduleA/file1@${rev} ${repo}/trunk/moduleB/file1 其中${repo}是您的存储库的URL, ${rev}是您想要的文件的版本。 这将恢复该文件的旧版本,包括最高版本