2013-11-23 33 views
1

我想在我的MVC ApiController中创建一个POST方法来接收并通过WebClient.UploadFile提交名称文件。我已经搜索了一段时间,并没有找到任何使用ApiController的完整样本。我发现很多使用MVC控制器使用的相同Request对象。这些全部使用Request.Files集合来获取文件流。但是,在ApiController公开的Request对象上找不到相同的属性。使用MVC ApiController接收通过WebClient.UploadFile上传的文件

以下是我的客户端控制台应用程序和服务器站点MVC ApiController的代码片段。

客户端代码:

private void executePost(string url, string filename, params KeyValuePair<string, string>[] parms) 
{ 
    WebClient client = new WebClient(); 
    parms.ToList().ForEach(k => client.QueryString.Add(k.Key, k.Value)); 
    client.UploadFile(url, "POST", filename); 
} 

和伪服务器端ApiController方法:

public async Task<HttpResponseMessage> UploadFile(string p1, string p2, string p3) 
{ 
    if (Request.Content.IsMimeMultipartContent()) 
    { 
     var provider = new MultipartFileStreamProvider("/myroot/files"); 
     await Request.Content.ReadAsMultipartAsync(provider) 
      .ContinueWith(r => 
      { 
       if (r.IsFaulted || r.IsCanceled) 
        throw new HttpResponseException(HttpStatusCode.InternalServerError); 
      }); 
     return Request.CreateResponse(HttpStatusCode.OK); 
    } 
} 

我如何去命名是要写入的文件。

感谢, 吉姆

+0

你上传一个文件?您的客户端代码是否发送多部分请求? –

回答

1

检查this StackOverflow上的问题。它为Web API 1和Web API 2

这是如何保存接收到的文件答案:

FileInfo fileInfo = new FileInfo(provider.FileData.First().LocalFileName); 
File.Move(fileInfo.FullName, "/path/to/destination");