簡體   English   中英

如何在ASP.NET Core Web API中上傳文件

[英]How to upload files in asp.net core web api

我正在嘗試在Asp.net Core中實現文件上傳。 請參閱下面的我的結局:

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

        // full path to file in temp location
        var filePath = Path.GetTempFileName();

        foreach (var formFile in files)
        {
            if (formFile.Length > 0)
            {
                using (var stream = new FileStream(filePath, FileMode.Create))
                {
                    await formFile.CopyToAsync(stream);
                }
            }
        }


        return Ok(new { count = files.Count, size, filePath });
    }

當我使用Postman測試它時,即使選擇任何文件,我也會得到以下結果:

{
   "count": 0,
   "size": 0,
   "filePath": "/var/folders/24/rmgj9ypj37709tnhxr2hgtfr0000gn/T/tmpX0SwbF.tmp"
}

這應該可以指導您正確的方向。 該方法正在接收jQuery post對象。

    [HttpPost]
    public async Task<IActionResult> ReadFileHeaders(IFormFile file)
    {
        if (file != null)
        {
            using (var stream = new MemoryStream())
            {
                await file.CopyToAsync(stream);
                // Now the file is loaded into the stream variable
            }
        }

        return BadRequest("File required");
    }

代碼沒有問題。 但是,在使用郵遞員(或類似的郵遞員)時,您需要在參數Illustration上使用相同的名稱(案件中的“文件”)

暫無
暫無

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

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