马上加入IBC程序猿 各种源码随意下,各种教程随便看! 注册 每日签到 加入编程讨论群

C#教程 ASP.NET教程 C#视频教程程序源码享受不尽 C#技术求助 ASP.NET技术求助

【源码下载】 社群合作 申请版主 程序开发 【远程协助】 每天乐一乐 每日签到 【承接外包项目】 面试-葵花宝典下载

官方一群:

官方二群:

C#Post传图片

[复制链接]
查看3958 | 回复0 | 2014-12-17 09:18:32 | 显示全部楼层 |阅读模式
先上代码
[C#] 纯文本查看 复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Drawing;
using System.Web;
using System.Net;
 
namespace postpic
{
    class postClass
    {
        /// <summary>
        /// 向服务器post文字和图片
        /// </summary>
        ///<param name="url">url
        ///<param name="userName">用户名
        ///<param name="userPwd">密码
        ///<param name="jpegPath">头像地址
        /// <returns>返回服务器返回值</returns>
        public string post(string url,string userName, string userPwd, string jpegPath)
        {
            //将图片转化为byte[]再转化为string
            string array = Convert.ToBase64String(imageToByteArray(jpegPath));
            //构造post提交字段
            string para = name=+userName+&pwd=+userPwd+&head=+HttpUtility.UrlEncode(array);
       
            #region HttpWebRequest写法
 
            HttpWebRequest httpWeb = (HttpWebRequest)WebRequest.Create(url);
            httpWeb.Timeout = 20000;
            httpWeb.Method = POST;
            httpWeb.ContentType = application/x-www-form-urlencoded;
            byte[] bytePara = Encoding.ASCII.GetBytes(para);
            using (Stream reqStream = httpWeb.GetRequestStream())
            {
                //提交数据
                reqStream.Write(bytePara, 0, para.Length);
            }
            //获取服务器返回值
            HttpWebResponse httpWebResponse = (HttpWebResponse)httpWeb.GetResponse();
            Stream stream = httpWebResponse.GetResponseStream();
            StreamReader streamReader = new StreamReader(stream, Encoding.GetEncoding(utf-8));
            //获得返回值
            string result = streamReader.ReadToEnd();
            stream.Close();
 
            #endregion
            //将服务器返回值返回
            return result;
        }
 
        /// <summary>
        /// 图片转为Byte字节数组
        /// </summary>
        ///<param name="FilePath">路径
        /// <returns>字节数组</returns>
        private byte[] imageToByteArray(string FilePath)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                using (Image imageIn = Image.FromFile(FilePath))
                {
                    using (Bitmap bmp = new Bitmap(imageIn))
                    {
                        bmp.Save(ms, imageIn.RawFormat);
                    }
                }
                return ms.ToArray();
            }
        }
    }
     
}


其实仔细看 很简单 就是把图片流转为Byte[]然后提交。 在服务器端 在用相同方法反着转回来就行了。

C#论坛 www.ibcibc.com IBC编程社区
C#
C#论坛
IBC编程社区
*滑块验证:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则