因为项目上需要用到文件上传且附带其他参数,需求是有一个winfrom程序要上传文件给netcore webapi 并且上传接口要能够支持多个参数的传递方式;期间也遇到了很多问题,随手记录一下,方便自己也也方便他人。
经过实验,采用multipart/form-data的方式可实现带文件、参数;此方法仅适用于小文件上传,大文件上传不建议使用。

示例代码

首先新建参数接收类 ,类中包含文件与其他参数;参数可自定义,代码如下:

public class Snapshot
    {
        public string directoy { get; set; }
        public int type { get; set; }
        public IFormFile picture { get; set; }
        public string id { get; set; }
    }

http post图片上传方法,如下代码:

[HttpPost("UploadSnaphot")]
        public async Task<HttpResponseMessage> UploadSnaphot([FromForm] Snapshot snapshot)
        {
            return await Task.Run(() =>
            {
                try
                {
                    if (snapshot == null)
                    {
                        return JsonManager.SimpleCustResponse("Invalid parameter");
                    }
                    else if (string.IsNullOrEmpty(snapshot.id))
                    {
                        return JsonManager.SimpleCustResponse("Invalid parameter warehouseId");
                    }
                    else if (snapshot.type != 0 && snapshot.type != 1)
                    {
                        return JsonManager.SimpleCustResponse("Invalid parameter type");
                    }
                    else if (string.IsNullOrEmpty(snapshot.directoy) || !DateTime.TryParseExact(snapshot.directoy, "yyyyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime _dir))
                    {
                        return JsonManager.SimpleCustResponse("Invalid parameter directoy");
                    }
                    else if (snapshot.picture == null)
                    {
                        return JsonManager.SimpleCustResponse("Invalid parameter picture");
                    }
                    else if (snapshot.picture.Length > 1024 * 1024 * 3)//3M
                    {
                        return JsonManager.SimpleCustResponse("file size too big");
                    }
                    else
                    {

                        //判断图片扩展名是否正确
                        List<string> extList = new List<string>()
                     {
                        ".png",
                        ".jpg"
                     };
                        var ext = Path.GetExtension(snapshot.picture.FileName).ToLower();
                        if (!extList.Contains(ext))
                        {
                            return JsonManager.SimpleCustResponse("unsupport media type");
                        }
                        else
                        {
                            
                            using (MemoryStream ms = new MemoryStream())
                            {
                                //拷贝文件到内存流
                                snapshot.picture.CopyTo(ms);
                                var tmp = ms.GetBuffer();
                                var fileType = tmp[0].ToString() + tmp[1].ToString();
                                //通过判断文件头类型判断是否图片格式,13780 png,255216 jpg
                                if (fileType == "13780" || fileType == "255216")
                                {
                                    var _path = “{_hostingEnvironment.WebRootPath}\\SnapPic\\TestUpload\\{snapshot.id.Replace("-", "")}\\{snapshot.directoy}";
                                    if (!Directory.Exists(_path))
                                    {
                                        Directory.CreateDirectory(_path);
                                    }
                                    Bitmap.FromStream(ms).Save([        DISCUZ_CODE_1        ]quot;{_path}\\{snapshot.picture.FileName}");
                                    return JsonManager.SimpleStatusResponse(ResultCode.OPERATE_SUCCESS);
                                }
                                else
                                {
                                    return JsonManager.SimpleCustResponse("unsupport media type");
                                }
                            }
                        }


                    }
                }
                catch (Exception ex)
                {
                    //_logger.LogError(ex.ToString());
                    return JsonManager.SimpleCustResponse("unsupport media type");
                }
            });
        }
最后修改:2022 年 09 月 29 日
如果觉得我的文章对你有用,请随意赞赏