C# net core webAPI 提供上传文件接口,并提供net core调用示例
时间: 2023-08-09 12:04:25 浏览: 113
好的,下面是一个基于C# .NET Core的WebAPI上传文件接口示例:
```csharp
[ApiController]
[Route("[controller]")]
public class FileUploadController : ControllerBase
{
private readonly ILogger<FileUploadController> _logger;
public FileUploadController(ILogger<FileUploadController> logger)
{
_logger = logger;
}
[HttpPost]
public async Task<IActionResult> Upload(IFormFile file)
{
try
{
if (file == null || file.Length == 0)
return Content("file not selected");
var filePath = Path.Combine(Path.GetTempPath(), file.FileName);
using (var stream = new FileStream(filePath, FileMode.Create))
{
await file.CopyToAsync(stream);
}
return Ok();
}
catch (Exception ex)
{
_logger.LogError(ex, "Error uploading file");
return StatusCode(500);
}
}
}
```
以上代码实现了一个简单的文件上传接口,接收一个名为“file”的文件参数,将其保存到临时目录中。
下面是一个.NET Core调用示例:
```csharp
public async Task UploadFile(string filePath)
{
using (var httpClient = new HttpClient())
{
using (var form = new MultipartFormDataContent())
{
using (var stream = new FileStream(filePath, FileMode.Open))
{
using (var memoryStream = new MemoryStream())
{
await stream.CopyToAsync(memoryStream);
var byteArrayContent = new ByteArrayContent(memoryStream.ToArray());
form.Add(byteArrayContent, "file", Path.GetFileName(filePath));
using (var response = await httpClient.PostAsync("http://localhost:5000/FileUpload", form))
{
response.EnsureSuccessStatusCode();
}
}
}
}
}
}
```
以上代码使用HttpClient将文件上传到WebAPI接口,其中“http://localhost:5000/FileUpload”是WebAPI的URL地址。
阅读全文