通过文件请求到Web API

问题描述

应用程序将文件发送到Web服务时遇到问题。这是我的端点/控制器。

[HttpPost]
    public async Task<IActionResult> Post(List<IFormFile> files)
    {
       
        long size = files.Sum(f => f.Length);

        foreach (var formFile in files)
        {
            if (formFile.Length > 0)
            {
                var filePath = "C:\\Files\\TEST.pdf";

                using (var stream = System.IO.File.Create(filePath))
                {
                    await formFile.copyToAsync(stream);
                }
            }
        }

此控制器在Postman中工作正常。

这是我的应用程序发出的请求:

             byte[] bytes = System.IO.File.ReadAllBytes("C:\\Files\\files.pdf");

             Stream fileStream = File.OpenRead("C:\\Files\\files.pdf");

             HttpContent bytesContent = new ByteArrayContent(bytes);
            
             using (var client = new HttpClient())
             using (var formData = new MultipartFormDataContent())
             {
                 formData.Add(bytesContent,"file","files.pdf");
                 try
                 {
                     var response = await client.PostAsync(url,formData);
                 }catch(Exception ex)
                 {
                     Console.WriteLine(ex);
                 }

它不起作用。我没有在控制器中收到文件。我也尝试过:

            string filetoUpload = "C:\\Files\\files.pdf";
            using (var client = new WebClient())
            {
                byte[] result = client.UploadFile(url,filetoUpload);
                string responseAsstring = Encoding.Default.GetString(result);
            }

,但结果相同。你能帮忙吗?

解决方法

更新15/09/2020

这是ConsoleApplication中的上传代码。它适用于小文件,但不适用于大文件。

    public static async Task upload(string url)
    {

        //const string url = "https://localhost:44308/file/post";
        const string filePath = "C:\\Files\\files.pdf";

        try { 
            using (var httpClient = new HttpClient{
                Timeout = TimeSpan.FromSeconds(3600)
            })
            {
                using (var form = new MultipartFormDataContent())
                {
                    using (var fs = System.IO.File.OpenRead(filePath))
                    {
                        fs.Position = 0;
                        using (var streamContent = new StreamContent(fs))
                        {
                            
                            form.Add(streamContent,"files",Path.GetFileName(filePath));
                            HttpResponseMessage response = httpClient.PostAsync(url,form).Result;
                            fs.Close();

                        }
                    }
                }
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }

    }




有两个步骤可以解决您的问题。

1。向标题添加ContentType

bytesContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");

2。 formData中的文件参数名称应与操作参数名称匹配。

formData.Add(bytesContent,"file","files.pdf"); //should be files


public async Task<IActionResult> Post(List<IFormFile> files)

更新

在控制台应用程序中等待

HttpClient.PostAsync()无效。而不是使用.Result进行阻止,请使用.GetAwaiter()。GetResult()。

HttpResponseMessage response = httpClient.PostAsync(url,form).Result;


这是显示如何上传文件的代码。

控制器代码

public class FileController : Controller
    {
        [HttpPost]
        public async Task<IActionResult> Post(List<IFormFile> files)
        {

            long size = files.Sum(f => f.Length);

            foreach (var formFile in files)
            {
                if (formFile.Length > 0)
                {
                    var filePath = "C:\\Files\\TEST.pdf";

                    using (var stream = System.IO.File.Create(filePath))
                    {
                        await formFile.CopyToAsync(stream);
                    }
                }
            }

            return Ok();
        }

        [HttpGet]
        public async Task<IActionResult> upload()
        {

            const string url = "https://localhost:44308/file/post";
            const string filePath = @"C:\\Files\\files.pdf";

            using (var httpClient = new HttpClient())
            {
                using (var form = new MultipartFormDataContent())
                {
                    using (var fs = System.IO.File.OpenRead(filePath))
                    {
                        using (var streamContent = new StreamContent(fs))
                        {
                            using (var fileContent = new ByteArrayContent(await streamContent.ReadAsByteArrayAsync()))
                            {
                                fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");

                                // "file" parameter name should be the same as the server side input parameter name
                                form.Add(fileContent,Path.GetFileName(filePath));
                                HttpResponseMessage response = await httpClient.PostAsync(url,form);
                            }
                        }
                    }
                }
            }

            return Ok();

        }
    }

测试

enter image description here