感谢https://www.youtube.com/watch?v=ungZ-BaVvZk&ab_channel=ThumbIKR-ProgrammingExamples的教程。
Net.Core Webapi 文件上传接口
Net版本 5.0
Controller设置
Controller文件夹,ImageUploadController.cs
文件,这里为了简化操作,将Model文件里面的 FileUploadAPI
也移到里面了。
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.IO;
namespace FileUploadStudy.Controllers
{
[Route("api/[Controller]")]
[ApiController]
public class ImageUploadController : ControllerBase
{
//初始化
public static IWebHostEnvironment _environment;
public ImageUploadController(IWebHostEnvironment environment)
{
_environment = environment;
}
public class FileUploadAPI
{
public IFormFile files { get; set; }
}
[HttpPost]
public async Task<string> Post([FromForm]FileUploadAPI objFile)
{
try
{
if (objFile.files.Length > 0)
{
string path = _environment.WebRootPath + "\\Upload\\";
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
using (FileStream filesStream= System.IO.File.Create(path + objFile.files.FileName))
{
objFile.files.CopyTo(filesStream);
filesStream.Flush();
return "\\Upload\\" + objFile.files.FileName;
}
}
else
{
return "false";
}
}
catch (Exception ex)
{
return ex.Message;
}
}
}
}
start.cs设置
start.cs文件的configure里面,主要改了三个部分
app.Run(async (context) =>
{
await context.Response.WriteAsync("文件不存在");
});
app.UseStaticFiles();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "FileUploadStudy v1"));
}
/// ---
else
{
app.UseHsts();
}
wwwroot
还有就是需要新建 wwwroot
文件夹
测试
注意关掉postman里面的ssl设置
文件上传接口做起来简单,但要注意几个细节,不然后面会浪费很多时间
- Post接口需要加上
[FromForm]
特性。不然postman测试会出现411,并且默认的Swagger接口测试也没有文件上传选项 - 注意key的值要与model的
FileUploadAPI
的files要对应上,不然也会报错