簡體   English   中英

請求文件到 Web API

[英]Request with file to 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, "files", Path.GetFileName(filePath));
                                HttpResponseMessage response = await httpClient.PostAsync(url, form);
                            }
                        }
                    }
                }
            }

            return Ok();

        }
    }

測試

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM