c# - 通过 ASP.NET MVC WebApi 上传文件的客户端代码

标签 c# asp.net-mvc file-upload asp.net-web-api2

我正在尝试编写代码以通过 WinForm 应用程序将文件上传到 WebApi。

WebApi 代码如下:

[HttpPost]
[Route("UploadEnvelope")]
[HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)]
public Task<HttpResponseMessage> PostUploadEnvelope()
{
    HttpRequestMessage request = this.Request;
    if (!request.Content.IsMimeMultipartContent())
    {
        throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
    }

    string root = System.Web.HttpContext.Current.Server.MapPath("~/App_Data/uploads");
    var provider = new MultipartFormDataStreamProvider(root);

    var task = request.Content.ReadAsMultipartAsync(provider).ContinueWith<HttpResponseMessage>(o =>
        {
            foreach (MultipartFileData fileData in provider.FileData)
            {
                if (string.IsNullOrEmpty(fileData.Headers.ContentDisposition.FileName))
                {
                    return Request.CreateResponse(HttpStatusCode.NotAcceptable, "This request is not properly formatted");
                }
                string fileName = fileData.Headers.ContentDisposition.FileName;
                if (fileName.StartsWith("\"") && fileName.EndsWith("\""))
                {
                    fileName = fileName.Trim('"');
                }
                if (fileName.Contains(@"/") || fileName.Contains(@"\"))
                {
                    fileName = Path.GetFileName(fileName);
                }
                File.Move(fileData.LocalFileName, Path.Combine(root, fileName));
            }

            return new HttpResponseMessage()
            {
                Content = new StringContent("Files uploaded.")
            };
        }
    );
    return task;
}

但我不知道如何调用它并在客户端应用程序中传递文件。

static string UploadEnvelope(string filePath, string token, string url)
{
    using (var client = new HttpClient())
    {
        client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);


        // How to pass file here ??? 

        var response = client.GetAsync(url + "/api/Envelope/UploadEnvelope").Result;

        return response.Content.ReadAsStringAsync().Result;
    }
}

欢迎任何帮助或建议。提前致谢!

最佳答案

首先,您使用用于读取的Get方法。您必须使用 Post 来代替。

尝试以下操作:

public static string UploadEnvelope(string  filePath,string token, string url)
{
    using (var client = new HttpClient())
    {
        client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
        using (var content = new MultipartFormDataContent("Envelope" + DateTime.Now.ToString(CultureInfo.InvariantCulture)))
        {
            content.Add(new StreamContent(new MemoryStream(File.ReadAllBytes(filePath))), "filename", "filename.ext");
            using (var message = await client.PostAsync(url + "/api/Envelope/UploadEnvelope", content))
            {
                var input = await message.Content.ReadAsStringAsync();
                return "success";
            }
        }
    }
}

注意:对于大文件,您必须更改 IIS web.config 上的配置。

关于c# - 通过 ASP.NET MVC WebApi 上传文件的客户端代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42633554/

相关文章:

c# - Visual Studio 2008 自定义类项模板,$safeprojectname$ 不协调

c# - EWS 读取邮件纯文本正文获取 ServiceObjectPropertyException

c# - "Input string was not in a correct format."C#

javascript - MVC 操作中引导日期到 C# 日期时间

c# - 仅显示 DateTime 中的日期

iOS 7后台上传和POST请求

c# - 找不到 Rx Dump() 方法

c# - 无法将 Linq.IOrderedEnumerable<T> 转换为 Linq.IQueryable<T>

java - 通过url上传文件

html - Amazon s3 文件上传到存储桶成功后不重定向