【问题标题】:Using MVC ApiController to receive file uploaded via WebClient.UploadFile使用 MVC ApiController 接收通过 WebClient.UploadFile 上传的文件
【发布时间】:2013-11-23 01:12:23
【问题描述】:

我试图在我的 MVC ApiController 中创建一个 POST 方法来接收和命名通过 WebClient.UploadFile 提交的文件。我已经搜索了一段时间,但没有找到任何使用 ApiController 的完整示例。我发现许多使用 MVC 控制器使用的相同请求对象。这些都使用 Request.Files 集合来获取文件流。但是,在 ApiController 公开的 Request 对象上找不到相同的属性。

以下是来自我的客户端控制台应用程序和服务器站点 MVC ApiController 的代码 sn-ps。

客户端代码:

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);
    }
}

如何命名要写入的文件。

谢谢, 吉姆

【问题讨论】:

  • 您上传的是单个文件吗?您的客户端代码是否发送多部分请求?

标签: c# asp.net-mvc asp.net-mvc-4 asp.net-web-api


【解决方案1】:

检查this StackOverflow 问题。它为 Web API 1 和 Web API 2 提供了答案。

这是保存接收到的文件的方法:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-09-17
    • 1970-01-01
    • 2010-11-02
    • 1970-01-01
    • 1970-01-01
    • 2011-06-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多