WebService上传下载图片

WebService服务端 接受要上传的图片

复制代码
public string UploadImg(byte[] fileBytes, int id)
{
    try
    {
        string filePath = MapPath(".") + "\EmpImage\" + id + ".jpg"; //图片要保存的路径及文件名
        using (MemoryStream memoryStream = new MemoryStream(fileBytes))//1.定义并实例化一个内存流,以存放提交上来的字节数组。
        {
            using (FileStream fileUpload = new FileStream(filePath, FileMode.Create))//2.定义实际文件对象,保存上载的文件。
            {
                memoryStream.WriteTo(fileUpload); ///3.把内存流里的数据写入物理文件  
            }
        }
        //GetSqlExcuteNonQuery是我写好的一个执行command的ExcuteNonQuery()方法
        GetSqlExcuteNonQuery(string.Format("insert into EmpImg values('{0}','{1}')", id, filePath)); //将该图片保存的文件路径写入数据库
    }
    catch (Exception ex)
    {
        return ex.Message;
    }
}
复制代码

WebService服务端 传递要下载的图片

复制代码
public byte[] LoadImg(string id)
{
    try
    {
        string path = GetSqlExcuteScalarStr("select Path from EmpImg where id='" + id + "'");
        FileInfo imgFile = new FileInfo(path);
        byte[] imgByte = new byte[imgFile.Length];  //1.初始化用于存放图片的字节数组 
        using (FileStream imgStream = imgFile.OpenRead()) //2.初始化读取图片内容的文件流
        {
            imgStream.Read(imgByte, 0, Convert.ToInt32(imgFile.Length));//3.将图片内容通过文件流读取到字节数组 
            return imgByte;
        }
    }
    catch
    {
        return null;
    }
}
复制代码

客户端的上传图片和下载图片同服务端的原理一样。只是客户端的上传图片要用到openFileDialog对话框

复制代码
internal void LocalImage(OpenFileDialog openF, PictureBox MyImage)
{
    openF.Filter = "*图片文件(*.jpg,*.gif,*.bmp)|*.jpg;*.gif;*.bmp";//筛选打开文件的格式
    if (openF.ShowDialog() == DialogResult.OK)//如果打开了图片文件
    {
        try
        {
            MyImage.Image = System.Drawing.Image.FromFile(openF.FileName);//设置PictureBox控件的Image属性 
        }
        catch
        {
            MessageBox.Show("您选择的图片不能被读取或文件类型不对!",//弹出消息对话框
                "错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }
    }
}
复制代码

然后就可以根据openFileDialog获取要上传的图片了

FileInfo imgFile = new FileInfo(openF.FileName);
原文地址:https://www.cnblogs.com/Brainpan/p/6650285.html