winform上传_下载

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Net;
using System.IO;

namespace TesterPoject
{
    public partial class procTest : Form
    {
        public procTest()
        {
            InitializeComponent();
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            myAdd();

            //using (SqlConnection conn = new SqlConnection())
            //{
            //    conn.ConnectionString = "Server=.;UId=william5;Pwd=william5;Database=testDb";
            //    conn.Open();

            //    using (SqlCommand commd = new SqlCommand())
            //    {
            //        commd.Connection = conn;
            //        commd.CommandType = CommandType.StoredProcedure;
            //        commd.CommandText = "proc_insert";

            //        SqlParameter[] parms = {
            //                                new SqlParameter("@userName",SqlDbType.VarChar,50),
            //                                new SqlParameter("@uPwd",SqlDbType.Int),
            //                                new SqlParameter("@createdate",SqlDbType.DateTime)
            //                               };
            //        parms[0].Value = this.txtName.Text;
            //        parms[1].Value = Convert.ToInt32(this.txtAge.Text);
            //        parms[2].Value = Convert.ToDateTime(this.txtCreatedate.Text);
            //        commd.Parameters.AddRange(parms);

            //        SqlParameter parmReturn = new SqlParameter("@return", SqlDbType.Int);
            //        parmReturn.Direction = ParameterDirection.ReturnValue;
            //        commd.Parameters.Add(parmReturn);

            //        SqlParameter parmOutput = new SqlParameter("@currentIdx",SqlDbType.VarChar,50);
            //        parmOutput.Direction = ParameterDirection.Output;
            //        commd.Parameters.Add(parmOutput);

            //        commd.ExecuteNonQuery();

            //        int iReturn = Convert.ToInt32(commd.Parameters["@return"].Value);
            //        if (iReturn == 1)
            //        {
            //            MessageBox.Show("添加成功");
            //            MessageBox.Show("当前的Idx=" + commd.Parameters["@currentIdx"].Value);
            //        }
            //        else
            //        {
            //            MessageBox.Show("添加失败");
            //        }

            //    }
            //}
        }

        private void myAdd()
        {
            //SqlConnection conn = new SqlConnection();
            //conn.ConnectionString = "Server=.;UId=william5;Pwd=william5;Database=testDb";
            //conn.Open();

            //SqlParameter[] parms = {SqlHelper.MakeInParameter("@userName", SqlDbType.VarChar, 50, this.txtName.Text),
            //            SqlHelper.MakeInParameter("@uPwd", SqlDbType.Int, this.txtAge.Text),
            //            SqlHelper.MakeInParameter("@createdate", SqlDbType.DateTime, this.txtCreatedate.Text),
            //            SqlHelper.MakeReturnParameter("@return", SqlDbType.Int),
            //            SqlHelper.MakeOutParameter("@currentIdx", SqlDbType.VarChar, 50)};

            //SqlHelper.ExecuteNonQuery(conn, CommandType.StoredProcedure, "proc_insert", parms);

            //MessageBox.Show(parms[3].Value.ToString()); //获取存储过程返回值
            //MessageBox.Show(parms[4].Value.ToString()); //获取存储过程输出参数
        }

        private void procTest_Load(object sender, EventArgs e)
        {
            //this.txtCreatedate.Text = DateTime.Now.ToShortDateString();
        }

        private void btnFileBrowser_Click(object sender, EventArgs e)
        {
            this.openFileDialog1.ShowDialog();
            this.txtPhoto.Text = this.openFileDialog1.FileName;
        }

        /**/
        /// <summary>
        /// WebClient上传文件至服务器
        /// </summary>
        /// <param name="fileNamePath">文件名,全路径格式</param>
        /// <param name="uriString">服务器文件夹路径</param>
        public void UpLoadFile(string fileNamePath, string uriString)
        {
            string fileName = fileNamePath.Substring(fileNamePath.LastIndexOf("\\") + 1);
            string NewFileName = fileName;

            string fileNameExt = fileName.Substring(fileName.LastIndexOf(".") + 1);
            if (uriString.EndsWith("/") == false) uriString = uriString + "/";

            uriString = uriString + NewFileName;
            /**/
            /// 创建WebClient实例
            WebClient myWebClient = new WebClient();
            myWebClient.Credentials = CredentialCache.DefaultCredentials;
            // 要上传的文件
            FileStream fs = new FileStream(fileNamePath, FileMode.Open, FileAccess.Read);
            //FileStream fs = OpenFile();
            BinaryReader r = new BinaryReader(fs);
            byte[] postArray = r.ReadBytes((int)fs.Length);
            Stream postStream = myWebClient.OpenWrite(uriString, "PUT");


            try
            {

                //使用UploadFile方法可以用下面的格式
                //myWebClient.UploadFile(uriString,"PUT",fileNamePath);
                if (postStream.CanWrite)
                {
                    postStream.Write(postArray, 0, postArray.Length);
                    postStream.Close();
                    fs.Dispose();
                }
                else
                {
                    postStream.Close();
                    fs.Dispose();
                }

            }
            catch (Exception err)
            {
                postStream.Close();
                fs.Dispose();
                throw err;
            }
            finally
            {
                postStream.Close();
                fs.Dispose();
            }
        }


        /// <summary>
        /// 下载服务器文件至客户端
        /// </summary>
        /// <param name="URL">被下载的文件地址,绝对路径</param>
        /// <param name="Dir">另存放的目录</param>
        public void Download(string URL, string Dir)
        {
            WebClient client = new WebClient();
            string fileName = URL.Substring(URL.LastIndexOf("\\") + 1);  //被下载的文件名

            string Path = Dir + fileName;   //另存为的绝对路径+文件名

            try
            {
                WebRequest myre = WebRequest.Create(URL);
            }
            catch (Exception err)
            {
                //MessageBox.Show(exp.Message,"Error");

            }

            try
            {
                client.DownloadFile(URL, fileName);
                FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
                BinaryReader r = new BinaryReader(fs);
                byte[] mbyte = r.ReadBytes((int)fs.Length);

                FileStream fstr = new FileStream(Path, FileMode.OpenOrCreate, FileAccess.Write);

                fstr.Write(mbyte, 0, (int)fs.Length);
                fstr.Close();

            }
            catch (Exception err)
            {

            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //上传图片
            string fileNamePath = txtPhoto.Text.Trim();
            string rootPath = Application.StartupPath;
            string serverFolder = string.Format(@"{0}/{1}", rootPath, "myImages");
            if (!Directory.Exists(serverFolder))
            {
                Directory.CreateDirectory(serverFolder);
            }
            UpLoadFile(fileNamePath, serverFolder);
            //保存到数据库
            SqlConnection conn = new SqlConnection();
            conn.ConnectionString = "Server=.;UId=william5;Pwd=william5;Database=testDb";
            conn.Open();
            string sql = string.Format("insert into tab_williamTest(sName,sPhoto) values('{0}','{1}')", this.txtName.Text, fileNamePath.Substring(fileNamePath.LastIndexOf("\\")+1));
            int iResult = SqlHelper.ExecuteNonQuery(conn, CommandType.Text, sql);
            if (iResult > 0)
            {
                MessageBox.Show("添加数据成功!");
            }

        }

        private void btnDownload_Click(object sender, EventArgs e)
        {

            string URL = @"G:\多媒体信息发布相关\QQLoginer\TesterPoject\TesterPoject\bin\Debug\myImages\1简历.doc";
            string Dir = @"G:\she1\";
            Download(URL, Dir);
        }

        private void btnFolder11_Click(object sender, EventArgs e)
        {
            this.openFileDialog1.ShowDialog();
            if (this.openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                this.txtFolder.Text = this.openFileDialog1.FileName.Substring(0, this.openFileDialog1.FileName.LastIndexOf("\\"));
            }
        }
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值