客户端代码通过ASP上传文件。净MVC WebApi

时间:2022-07-10 03:44:18

I am trying to write code to upload file(s) by WinForm app to WebApi.

我正在尝试编写WinForm app将文件上传到WebApi的代码。

The WebApi code is like:

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

But I am not sure how to call it and pass file in a client app.

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

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

Any help or suggestion is welcome. Thanks in advance!

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

1 个解决方案

#1


1  

First you are using Get method which is used for reading. You have to use Post instead.

首先,您使用的是用于阅读的Get方法。你必须用Post代替。

Try the following:

试试以下:

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

Note: For a large file you have to change configuration on IIS web.config.

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

#1


1  

First you are using Get method which is used for reading. You have to use Post instead.

首先,您使用的是用于阅读的Get方法。你必须用Post代替。

Try the following:

试试以下:

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

Note: For a large file you have to change configuration on IIS web.config.

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