.netcore3.1 winfrom 实现文件上传

说明:实现文件的上传功能。后端使用.net core3.1作为接口服务,用于接收文件。前端使用winfrom 实现文件上传。

 

1、.net core3.1 实现webApi接口。

 

 

 

 

 

 

 

 

 

        /// <summary>
        /// 客户端:上传图片、视频
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("postUploadFile")]
        public ResultObject postUploadFile() {
            ResultObject result = new ResultObject();
            try {
                IFormFileCollection files = Request.Form.Files;
                foreach (IFormFile file in files) {
                    //目录
                    string directory = Path.Combine(Directory.GetCurrentDirectory(), "Upload");
                    if (!Directory.Exists(directory)) {
                        Directory.CreateDirectory(directory);
                    }
                    string filePath = Path.Combine(directory, file.FileName);
                    // 写入文件
                    using (var stream = new FileStream(filePath, FileMode.Create)) {
                        file.CopyTo(stream);
                        stream.Flush();
                    }
                }
                result = CommonResult.success();
            }
            catch (Exception vErr) {
                result = CommonResult.failure(vErr.Message);
            }
            return result;
        }

2、winfrom 项目代码

 

 

 

   public class UploadFileHelper {

        /// <summary>
        /// Http Post 可传文件参数
        /// </summary>
        /// <param name="dic">字符串 字典数据</param>
        /// <param name="dicFile">文件 字典数据</param>
        /// <returns></returns>
        public bool PostJsonDataFile(Dictionary<string, string> dic, Dictionary<string, KeyValuePair<string, byte[]>> dicFile) {
            bool vCheck = true;
            string str = "";
            try {
                string url = ConfigurationManager.AppSettings["UploadFileUrl"].ToString();

                Uri uri = new Uri(url);
                var httpclientHandler = new HttpClientHandler();
                HttpClient client = new HttpClient(httpclientHandler);
                client.Timeout = Timeout.InfiniteTimeSpan;
                var form = new MultipartFormDataContent();
                string boundary = string.Format("--{0}", DateTime.Now.Ticks.ToString("x"));
                form.Headers.Add("ContentType", $"multipart/form-data, boundary={boundary}");
                if (dic != null) {
                    foreach (var key in dic.Keys) {
                        form.Add(new StringContent(dic[key].ToString()), key);
                    }
                }
                if (dicFile != null) {
                    foreach (var key in dicFile.Keys) {
                        var fileContent = new ByteArrayContent(dicFile[key].Value);
                        fileContent.Headers.ContentType = new MediaTypeHeaderValue("text/plain");
                        form.Add(fileContent, name: key, fileName: dicFile[key].Key);
                    }
                }

                Util.SetCertificatePolicy();//为SSL/TLS 安全通道建立信任关系

                HttpResponseMessage response = client.PostAsync(url, form).Result;
                str = response.Content.ReadAsStringAsync().Result;
            }
            catch (Exception vErr) {
                vCheck = false;
                str = vErr.Message;
            }
            return vCheck;
        }


    }

    public static class Util {

        /// <summary>
        /// Sets the cert policy.
        /// </summary>
        public static void SetCertificatePolicy() {
            ServicePointManager.ServerCertificateValidationCallback += RemoteCertificateValidate;
        }

        /// <summary>
        /// Remotes the certificate validate.
        /// </summary>
        private static bool RemoteCertificateValidate(
           object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors error) {
            // trust any certificate!!!
            System.Console.WriteLine("Warning, trust any certificate");
            return true;
        }
    }

 

 

 

 

 

                            string vName = DateTime.Now.ToString("yyyyMMddHHmmssffff") + "_" + new Random().Next(1, 10000) + System.IO.Path.GetExtension(vFileNames[i]);
                            //上传图片
                            if (vCheck) {
                                Dictionary<string, KeyValuePair<string, byte[]>> vParam = new Dictionary<string, KeyValuePair<string, byte[]>>();
                                vParam.Add("imageFile", new KeyValuePair<string, byte[]>(vName, System.IO.File.ReadAllBytes(vFileNames[i])));

                                UploadFileHelper uploadFile = new UploadFileHelper();
                                vCheck = uploadFile.PostJsonDataFile(null, vParam);
                            }

 

posted @ 2022-08-05 16:58  许宝  阅读(198)  评论(0编辑  收藏  举报