Net Core教程

C#图片上传

本文主要是介绍C#图片上传,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

个人在项目开发时用到的分享出来,不足之处还请各位指正

```csharp
//.net farmworker版本低的可以用这个
public JObject UploadFace(string path)
        {
        //接口地址
            string url = "http://1.1.1.1/Post";
            string appKey = "321321";
            string appSecret = "12345678";
            //获取当前时间
            DateTime dt = DateTime.Now;
            //获取时间戳
            string strtimestamp = ConvertDateTimeToInt(dt).ToString();
            string strSign = GetMD5(strtimestamp + "#" + appSecret);
            url += string.Format("?sign={0}&app_key={1}&timestamp={2}", strSign, appKey, strtimestamp);

            JObject json = null;
            WebRequest wrequse = null;
            HttpWebRequest request = null;
            Stream postStream = null;
            HttpWebResponse response = null;
            try
            {
                int pos = path.LastIndexOf("\\");
                //获取文件名
                string fileName = path.Substring(pos + 1);
                //读取文件
                using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
                {
                //打开接口
                    wrequse = WebRequest.Create(url);
                    // 设置参数
                    request = (wrequse as HttpWebRequest);
                    //允许重定向
                    request.AllowAutoRedirect = true;
                    request.Timeout = 5000;
                    //请求方式 
                    request.Method = "POST";
                    // 随机分隔线
                    string boundary = DateTime.Now.Ticks.ToString("X");
                    request.ContentType = "multipart/form-data;charset=utf-8;boundary=" + boundary;
                    byte[] itemBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n");
                    byte[] endBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");
                    //请求头部信息 
                    StringBuilder sbHeader = new StringBuilder(string.Format("Content-Disposition:form-data;name=\"face_avatar\";filename=\"{0}\";\r\nContent-Type:image/Jpeg\r\n\r\n", fileName));
                    byte[] postHeaderBytes = Encoding.UTF8.GetBytes(sbHeader.ToString());
                    byte[] bArr = new byte[fs.Length];
                    fs.Read(bArr, 0, bArr.Length);
                    fs.Close();
                    fs.Dispose();
                    sbHeader = null;
                    using ( postStream = request.GetRequestStream())
                    {
                        postStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length);
                        postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
                        postStream.Write(bArr, 0, bArr.Length);
                        postStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
                    }
                    bArr = null;
                    postHeaderBytes = null;
                    endBoundaryBytes = null;
                    itemBoundaryBytes = null;
                    using (response = (HttpWebResponse)request.GetResponse())
                    {
                        Stream instream = null;
                        try
                        {
                            using (instream = response.GetResponseStream())
                            {
                                StreamReader sr = null;
                                try
                                {
                                    using (sr = new StreamReader(instream, Encoding.UTF8))
                                    {
                                        json = JObject.Parse(sr.ReadToEnd());
                                    }
                                }
                                finally
                                {
                                    sr.Close();
                                    sr.Dispose();
                                }
                            }
                        }
                        finally
                        {
                            instream.Close();
                            instream.Dispose();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                if (ex.Message.IndexOf("服务器") >= 0)
                    UMessageBoxError("服务器未响应!");
                return null;
            }
            finally
            {

                if (response != null) { 
                    response.Close();
                    response.Dispose();
                }
                if (postStream != null)
                {
                    postStream.Close();
                    postStream.Dispose();
                }
                if (request != null)
                    request.Abort();
                if (wrequse != null)
                    wrequse.Abort();
            }
            return json;
        }

 //获取时间戳
        public static long ConvertDateTimeToInt(DateTime time)
        {
            DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1, 0, 0, 0, 0));
            long t = (time.Ticks - startTime.Ticks) / 10000;  //除10000调整为13位   
            return t;
        }

/// <summary>
        /// .net farmworker 4.52及以上
        /// </summary>
        /// <param name="filepath"></param>
        /// <returns></returns>
        public string HttpSendFormData(string filepath)
        {
            string strUrl  = "http://1.1.1.1/Post";
            string appKey = "2123123";
            string appSecret = "231231321";
            DateTime dt = DateTime.Now;
            string strtimestamp = ConvertDateTimeToInt(dt).ToString();
            string strSign = GetMD5(strtimestamp + "#" + appSecret);
            strUrl += string.Format("?sign={0}&app_key={1}&timestamp={2}", strSign, appKey, strtimestamp);
            RestClient client = new RestClient(strUrl);
            client.Timeout = 4000;
            client.ReadWriteTimeout = 4000;
            RestRequest request = new RestRequest(Method.POST)
            {
                AlwaysMultipartFormData = true
            };
            try
            {

                using (FileStream fs = new FileStream(filepath, FileMode.Open, FileAccess.Read))
                {
                    byte[] _bytes = new byte[fs.Length];
                    fs.Read(_bytes, 0, _bytes.Length);
                    fs.Close();
                    fs.Dispose();
                    request.AddHeader("Content-Type", "multipart/form-data");
                    request.AddFile("face_avatar", _bytes, "jjjj_aaa_1.jpg", "image/jpeg");
                    _bytes = null;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            IRestResponse response = client.Execute(request);
            client.ClearHandlers();
            
            string strText = response.Content;

            return strText;
        }

                    
这篇关于C#图片上传的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!