IO流,C# 上传文件并保存,然后读取出该文件显示在页面

//上传照片
private void Add_Image(object sender, MouseButtonEventArgs e)
{
MyCustomControlLibrary.MMessageBox.ShowLoading(MyCustomControlLibrary.MMessageBox.LoadType.rander
, “Loading…”, new Point(0, 0), new Size(0, 0), “”, System.Windows.Controls.Orientation.Vertical, “#ffffff”, 9000);
Stream photo = null;
int length;
Microsoft.Win32.OpenFileDialog ofFile = new Microsoft.Win32.OpenFileDialog();
ofFile.Multiselect = true;
ofFile.Filter = “ALL Image Files|.”;
MyCustomControlLibrary.MMessageBox.MClosed();
if (Convert.ToBoolean(ofFile.ShowDialog()))
{
if ((photo = ofFile.OpenFile()) != null)
{
length = Convert.ToInt32(photo.Length);
byte[] bytes = new byte[length];
photo.Read(bytes,0,length);

                //保存byte数组(图片)
                DateTime dt = DateTime.Now;
                string dateTime_path = dt.Year.ToString() + dt.Month.ToString() + dt.Day.ToString() + dt.Hour.ToString() + dt.Minute.ToString() + dt.Second.ToString() + ".jpg";
                Application.Current.Properties["_01QianTai_Window1_CustomerPhotePath"] = dateTime_path;//Session存储照片
                string CustomerPhotoPath = System.AppDomain.CurrentDomain.BaseDirectory + "_08Server_Img\\CustomerPhoto\\";//保存顾客照片的文件夹
                if (!System.IO.Directory.Exists(CustomerPhotoPath)) System.IO.Directory.CreateDirectory(CustomerPhotoPath);

                File.WriteAllBytes(CustomerPhotoPath + dateTime_path, bytes);
                APicture.Source = GetImage(CustomerPhotoPath + dateTime_path);
            }
        }
        else
        {
            //提示,没有该插件,请随意给一个提示,或者直接不写代码
            MyCustomControlLibrary.MMessageBox.ShowAlert("未选择任何照片。", Orientation.Horizontal, null, "LightCyan", false, true, 2);
            APicture.Source = GetImage(System.AppDomain.CurrentDomain.BaseDirectory + "_08Server_Img\\A_AddImage.PNG");
        }
    }



    //释放资源
    public static BitmapImage GetImage(string imagePath)
    {
        BitmapImage bitmap = new BitmapImage();

        if (File.Exists(imagePath))
        {
            bitmap.BeginInit();
            bitmap.CacheOption = BitmapCacheOption.OnLoad;

            using (Stream ms = new MemoryStream(File.ReadAllBytes(imagePath)))
            {
                bitmap.StreamSource = ms;
                bitmap.EndInit();
                bitmap.Freeze();
            }
        }
        else
        {
            bitmap.BeginInit();
            bitmap.CacheOption = BitmapCacheOption.OnLoad;
            string System_ = System.AppDomain.CurrentDomain.BaseDirectory + "_08Server_Img//Simages//V_02.png";
            using (Stream ms = new MemoryStream(File.ReadAllBytes(System_)))
            {
                bitmap.StreamSource = ms;
                bitmap.EndInit();
                bitmap.Freeze();
            }
        }

        return bitmap;
    }

客户端代码:

发布了115 篇原创文章 · 获赞 36 · 访问量 9881

猜你喜欢

转载自blog.csdn.net/weixin_44548307/article/details/103477703