How To Accept a File POST

前端 未结 13 1602
深忆病人
深忆病人 2020-11-22 09:48

I\'m using asp.net mvc 4 webapi beta to build a rest service. I need to be able to accept POSTed images/files from client applications. Is this possible using the webapi?

13条回答
  •  青春惊慌失措
    2020-11-22 09:58

    The ASP.NET Core way is now here:

    [HttpPost("UploadFiles")]
    public async Task Post(List 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);
                }
            }
        }
    
        // process uploaded files
        // Don't rely on or trust the FileName property without validation.
    
        return Ok(new { count = files.Count, size, filePath});
    }
    

提交回复
热议问题