南希:解析" multipart / form-data"要求

时间:2016-02-16 07:57:00

标签: rest restsharp nancy

我有一个RestSharp客户端和Nancy Self Host Server。 我想要的是

  

从客户端发送多部分表单数据并轻松解析该数据   来自服务器:

     

从RestSharp客户端发送二进制文件和Json数据作为多部分表单数据   并且能够从Nancy Server获取二进制文件和Json对象

在客户端使用Restsharp:[http://restsharp.org/]我尝试发送" multipart / form-data"请求包含二进制文件加上一些json格式的元数据:

var client = new RestClient();
...

IRestRequest restRequest = new RestRequest("AcmeUrl", Method.POST);

restRequest.AlwaysMultipartFormData = true;
restRequest.RequestFormat = DataFormat.Json;

// I just add File To Request
restRequest.AddFile("AudioData", File.ReadAllBytes("filePath"), "AudioData");

// Then Add Json Object
MyObject myObject = new MyObject();
myObject.Attribute ="SomeAttribute";
....

restRequest.AddBody(myObject);

client.Execute<MyResponse>(request);

在使用Nancy [http://nancyfx.org/]的服务器上,Itry获取文件和Json对象[元数据]

// Try To Get File : It Works
var file = Request.Files.FirstOrDefault();


// Try To Get Sended Meta Data Object  : Not Works. 
// Can Not Get MyObject Data

MyObject myObject = this.Bind<MyObject>();

1 个答案:

答案 0 :(得分:2)

对于多部分数据,Nancy的代码有点复杂。 尝试这样的事情:

public ArrayList<String> getAllCountriesCheck(String l) {
        ArrayList<String> list = new ArrayList<String>();
        PreparedStatement ps = null;
        String data;
        try {
            String ch=l+"%";
            ps = (PreparedStatement) dcon.con.prepareStatement("SELECT nicename FROM tbctry  WHERE nicename  LIKE '"+ch+"'");
            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                data = rs.getString("nicename");
                System.out.println(data);
                list.add(data);
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return list;
    }

看看: http://www.applandeo.com/en/net-and-nancy-parsing-multipartform-data-requests/