WebClient上传文件到ashx

Client

---------------------


    public delegate void GenHandler<T>(T obj);

    public partial class frmFileUpload : Form
    {
        string filePath = string.Empty;

        public frmFileUpload()
        {
            InitializeComponent();
        }

        private void btnUploadFileToWebService_Click(object sender, EventArgs e)
        {
            OpenFileDialog dg = new OpenFileDialog();
            dg.Multiselect = false;
            if (dg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                filePath = dg.FileName;
                WebClient client = new WebClient();
                client.Credentials = CredentialCache.DefaultCredentials;
                client.OpenWriteCompleted += client_OpenWriteCompleted;

                UriBuilder ub = new UriBuilder("http://...ashx");
                ub.Query = string.Format("fileName={0}", new FileInfo(filePath).Name);
                client.OpenWriteAsync(ub.Uri);
            }
        }

        void client_OpenWriteCompleted(object sender, OpenWriteCompletedEventArgs e)
        {
            if (File.Exists(filePath))
            {
                System.IO.BinaryReader r = new System.IO.BinaryReader(File.OpenRead(filePath));
                while (r.BaseStream.Position < r.BaseStream.Length - 1)
                {
                    byte[] bts = r.ReadBytes(10);
                    if (bts.Length > 0)
                    {
                        e.Result.Write(bts, 0, bts.Length);
                        int per = (int)(((r.BaseStream.Position + 1) * 100) / r.BaseStream.Length);
                        string strPer = string.Format("{0}%", per);
                        OutPutProgress(strPer);
                    }
                }
                e.Result.Close();
                r.Close();
            }
        }

        private void OutPutProgress(string progress)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new GenHandler<string>(OutPutProgress), progress);
            }
            else
            {
                this.Text = progress;
            }
        }
    }

 

Service

---------------------


    /// <summary>
    /// 文档数据存储服务
    /// </summary>
    public class DocReceiver : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            context.Response.Write("文档数据存储服务。\r\n");

            try
            {
                context.Response.Write("数据接收开始...\r\n");

                string id = context.Request.Form["docId"];
                string fileName = context.Request.QueryString["fileName"];
                if (string.IsNullOrEmpty(fileName))
                {
                    fileName = DateTime.Now.ToString("yyMMddHHmmss_") + Guid.NewGuid().ToString() + ".xls";
                }
                else
                {
                    fileName = DateTime.Now.ToString("yyMMddHHmmss_") + fileName;
                }
                string path = context.Server.MapPath("~/[upload]/" + fileName);
                Stream inStream = context.Request.InputStream;
                if (inStream != null && inStream.Length > 0)
                {
                    FileInfo fi = new FileInfo(path);
                    if (!fi.Directory.Exists)
                    {
                        fi.Directory.Create();
                    }
                    using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write))
                    {
                        int count;
                        byte[] buffer = new byte[1024];
                        while ((count = inStream.Read(buffer, 0, 1024)) > 0)
                        {
                            fs.Write(buffer, 0, count);
                        }
                    }
                }

                context.Response.Write("数据接收完毕。\r\n");
            }
            catch (Exception ex)
            {
                context.Response.Write("数据接收失败。\r\n");
                context.Response.Write(ex.Message + "\r\n");
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值