webapi接收前端上传图片

上传图片后,前端如何根据返回的地址来获取图片,见下一篇文章: https://www.cnblogs.com/tlfe/p/18926730
项目中可直接拿过来使用
新建webapi项目,目录如下

 ApiResult是封装的统一返回格式

namespace WebApplication1.Common
{
    /// <summary>
    /// Api返回数据的时候,统一格式
    /// 1. 方便前端调用访问数据
    /// 2. 如果服务器发生了错误、异常之后,也是给包装成ApiResult返回
    /// </summary>
    public class ApiResult
    {
        /// <summary>
        /// 是否正常返回---状态
        /// </summary>
        public bool Success { get; set; }

        /// <summary>
        /// 处理消息
        /// </summary>
        public string? Message { get; set; }
    }


    public class ApiDataResult<T> : ApiResult
    {
        /// <summary>
        /// 结果集
        /// </summary>
        public T? Data { get; set; }

        /// <summary>
        /// 冗余结果
        /// </summary>
        public object? OValue { get; set; }
    }
}

CustomSwagerExt 为 Swagger扩展类

using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;

namespace upoedImg.Utility.SwaggetExt
{
    public static class CustomSwaggerExt
    {
        public static void AddSwaggerExt(this WebApplicationBuilder builder)
        {
            builder.Services.AddEndpointsApiExplorer();
            builder.Services.AddSwaggerGen(option =>
            {
                option.OperationFilter<SwaggerFileUploadFilter>();
            });
        }

    }
    /// <summary>
    /// 给swagger上添加文件上传按钮,方便测试
    /// </summary>
    public class SwaggerFileUploadFilter : IOperationFilter
    {
        public void Apply(OpenApiOperation operation, OperationFilterContext context)
        {
            const string FileUploadContentType = "multipart/form-data";
            if (operation.RequestBody == null ||
                !operation.RequestBody.Content.Any(x =>
                x.Key.Equals(FileUploadContentType, StringComparison.InvariantCultureIgnoreCase)))
            {
                return;
            }

            if (context.ApiDescription.ActionDescriptor.Parameters.Any(c => c.ParameterType == typeof(IFormFile)))
            {
                operation.RequestBody = new OpenApiRequestBody
                {
                    Description = "文件上传 可以自己定义各种文字",
                    Content = new Dictionary<string, OpenApiMediaType>
                    {
                         {
                            FileUploadContentType, new OpenApiMediaType
                            {
                                Schema = new OpenApiSchema
                                {
                                    Type = "object",
                                    Required = new HashSet<string>{ "file" },
                                    Properties = new Dictionary<string, OpenApiSchema>
                                    {
                                        {
                                            "file", new OpenApiSchema()
                                            {
                                                Type = "string",
                                                Format = "binary"
                                            }
                                        }
                                    }
                                }
                            }
                         }
                    }
                };
            }
        }
    }

}

 

UploadFileController为文件接收控制器

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using upoedImg.Common;

namespace upoedImg.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class UpLoadImgController : ControllerBase
    {
        private readonly ILogger<UpLoadImgController> _logger;
        public UpLoadImgController(ILogger<UpLoadImgController> logger)
        {
            _logger = logger;
        }
        /// <summary>
        /// 文件上传的API
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> UploadFiles([FromForm] IFormFile file)
        {
            // 1. 验证文件是否为空
            if (file == null || file.Length == 0)
            {
                return new JsonResult(new ApiDataResult<string>()
                {
                    Success = false,
                    Message = "请选择有效的文件"
                });
            }

            // 2. 验证文件大小(例如限制为10MB)
            if (file.Length > 10 * 1024 * 1024)
            {
                return new JsonResult(new ApiDataResult<string>()
                {
                    Success = false,
                    Message = "文件大小不能超过10MB"
                });
            }

            // 3. 验证文件扩展名
            var allowedExtensions = new[] { ".jpg", ".jpeg", ".png", ".gif" };
            string fileExtension = Path.GetExtension(file.FileName).ToLowerInvariant();

            if (string.IsNullOrEmpty(fileExtension) || !allowedExtensions.Contains(fileExtension))
            {
                return new JsonResult(new ApiDataResult<string>()
                {
                    Success = false,
                    Message = "仅支持上传图片文件(JPG, JPEG, PNG, GIF)"
                });
            }

            // 4. 准备保存路径
            string saveDirectory = Path.Combine("FileUpload", DateTime.Now.ToString("yyyy-MM-dd"));
            string allSavePath = Path.Combine(Directory.GetCurrentDirectory(), saveDirectory);

            if (!Directory.Exists(allSavePath))
            {
                Directory.CreateDirectory(allSavePath);
            }

            // 5. 生成唯一文件名(使用Guid更安全)
            string newFileName = $"{DateTime.Now:yyyyMMddHHmmss}_{Guid.NewGuid()}{fileExtension}";
            string allSaveFilePath = Path.Combine(allSavePath, newFileName);

            try
            {
                // 6. 异步保存文件
                using (var stream = new FileStream(allSaveFilePath, FileMode.Create))
                {
                    await file.CopyToAsync(stream);
                }

                // 7. 返回相对路径(更安全)
                string relativePath = Path.Combine(saveDirectory, newFileName).Replace("\\", "/");

                return new JsonResult(new ApiDataResult<string>()
                {
                    Success = true,
                    Message = "文件上传成功",
                    Data = relativePath
                });
            }
            catch (Exception ex)
            {
                // 记录日志
                _logger.LogError(ex, "文件上传失败");

                return new JsonResult(new ApiDataResult<string>()
                {
                    Success = false,
                    Message = "文件上传失败,请稍后再试"
                });
            }
        }
    }
}

 

FileUpload文件为存放图片地址

 

posted @ 2025-06-12 17:59  龙卷风吹毁停车场  阅读(18)  评论(0)    收藏  举报