好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

winform如何上传图片到服务器

winform如何上传图片到服务器

有BS网站一个,然后,我添加产品要通过winform来添加,可是,图片怎么上传到服务器指定目录呢?

C#初学者,所以提的问题对各位前辈朋友来说可能很简单,也可能问法也不对,非常期待大家的回答……

您好

請參考 WebClient.UploadFile 方法 : 将本地文件上载到具有指定 URI 的资源。

http://msdn.microsoft.com/zh-cn/library/bcfh1hw9(v=VS.80).aspx

您好,

winform 上传图片到服务器,您可以根据不同的需求使用不同的方法,之前 Stone 和小欧的方法都可以,下面还有一些您可以参考一下:

1 、通过 TextBox 上传图片到服务器: http://blog.csdn.net/anya/archive/2009/06/15/4270508.aspx

2 、自己写一个 SOCKET 客户端,和一个 SOCKET 服务端: http://www.cnblogs.com/steven-mo/archive/2008/06/24/1228857.html

3 、使用 Uploader.ashx 方法: http://hi.baidu.com/longyi98/blog/item/7247b924a0b11b26d507426c.html

希望以上内容对您有所帮助。最后请把对您有帮助的回复 “ 标记为答复 ” ,这样可以更好的帮助论坛里其他和您遇到类似问题的朋友。

谢谢您的理解和支持!

放到同一目录,只记住文件名,然后用一次传上去

http://feiyun0112.cnblogs.com/

Socket网络传输(C#)

  如果想要利用C#通过Socket进 行网络传输文件,一般情况下,大家会首先考虑使用.NET自带的Socket.SendFile Method (String)这个方法。不过这个方法没有相应的文件接受方法,而且据说会有8KB的限制。所以,我尝试了另外一种方法,发现效果不错。下面,我就来简 单介绍一下其原理。
  Socket.Send()和Socket.Receive()方法都是传递byte[]的,所以就要想办法把文件给变成byte[]。一开始试过用 StreamReader来读取string,然后用Encoding来进行编码得到byte[],接收以后再还原成string写入文件。结果发现不可 行,只有纯文本文件以这种方法传输是正常的。
  无奈之下,只好另想办法。后来在File类下找到了这两个方法——File.ReadAllBytes()和 File.WriteAllBytes()。试了一下用这两个方法来把文件变成byte[],再把byte[]还原成文件,结果成功了!(试过了传输图片 和rar压缩文件,都OK!)

  有兴趣的朋友,可以到这里下载源码:http://download.csdn.net/source/511058(原创代码)

网上有很多方案,起初用时,因为对asp.net不太了解,觉得FTP实现不错,可是后来发现,如果机器在域控下,就会有问题。

一年过去了,asp.net也熟悉了,知道ajax没事应该用ashx,验证码也用ashx,当然这里要说的WinForm上传也应该是ashx了 吧,哈哈,先提供简单思路:

接收文件的asp.net是:Uploader.ashx,相关代码:

view plain copy to clipboard print ?

<%@ WebHandler Language= "C#"  Class= "Uploader"  %>   using  System;   using  System.IO;   using  System.Web;      public   class  Uploader : IHttpHandler   {        public   void  ProcessRequest(HttpContext hc)       {            foreach  ( string  fileKey  in  hc.Request.Files)           {               HttpPostedFile file = hc.Request.Files[fileKey];               file.SaveAs(Path.Combine(hc.Server.MapPath( "." ), file.FileName));           }       }           public   bool  IsReusable       {            get  {  return   true ; }       }   }  

 发送图片或文件的WinForm.cs 相关代码:

view plain copy to clipboard print ?

System.Net.WebClient myWebClient =  new  System.Net.WebClient();   myWebClient.UploadFile( "http://www.yongfa365.com/Uploader.ashx" ,  "POST" ,  "C:\\WINDOWS\\system32\\cmd.exe" );  

OK,完了,这样操作后,再也不用管是不是在域控内了,只要能上网,就能上传。够方便吧。

如果你要批量上传,还有上传后保存在哪个目录等操作可以参考 柳永法 (yongfa365)'Blog 写的:

接收文件的asp.net是:Uploader.ashx,相关代码:

view plain copy to clipboard print ?

<%@ WebHandler Language= "C#"  Class= "Uploader"  %>   using  System;   using  System.IO;   using  System.Web;      public   class  Uploader : IHttpHandler   {        public   void  ProcessRequest(HttpContext hc)       {            string  NowPath = Path.Combine(hc.Server.MapPath( "." ), hc.Request[ "path" ]);               if  (!Directory.Exists(NowPath))           {               Directory.CreateDirectory(NowPath);           }               foreach  ( string  fileKey  in  hc.Request.Files)           {               HttpPostedFile file = hc.Request.Files[fileKey];                string  FilePath = Path.Combine(NowPath, file.FileName);                if  (File.Exists(FilePath))               {                    if  (Convert.ToBoolean(hc.Request[ "overwrite" ]))                   {                       File.Delete(FilePath);                   }                    else                    {                        continue ;                   }               }               file.SaveAs(FilePath);           }       }           public   bool  IsReusable       {            get  {  return   true ; }       }   }  

 发送图片或文件的WinForm.cs 相关代码:

view plain copy to clipboard print ?

string  url = @ "http://www.yongfa365.com/Uploader.ashx?Overwrite=true&PATH=Logs\" + DateTime.Now.ToString(" yyyy-MM-dd");   foreach  ( string  file  in  Directory.GetFiles(item))   {       System.Net.WebClient myWebClient =  new  System.Net.WebClient();       myWebClient.UploadFile(url,  "POST" , file);   } 

Winform如何通过TextBox上传图片到服务器
2009-06-15 15:11 1045人阅读 评论(9) 收藏 举报

      #region Windows 窗体设计器生成的代码

        /// <summary>
        /// 设计器支持所需的方法 - 不要
        /// 使用代码编辑器修改此方法的内容。
        /// </summary>
        private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            this.button1 = new System.Windows.Forms.Button();
            this.textBox1 = new System.Windows.Forms.TextBox();
            this.linkLabel1 = new System.Windows.Forms.LinkLabel();
            this.button2 = new System.Windows.Forms.Button();
            this.txtFileName = new System.Windows.Forms.TextBox();
            this.label3 = new System.Windows.Forms.Label();
            this.txtServerPath = new System.Windows.Forms.TextBox();
            this.label2 = new System.Windows.Forms.Label();
            this.button3 = new System.Windows.Forms.Button();
            this.label1 = new System.Windows.Forms.Label();
            this.timer1 = new System.Windows.Forms.Timer(this.components);
            this.pictureBox1 = new System.Windows.Forms.PictureBox();
            this.button4 = new System.Windows.Forms.Button();
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
            this.SuspendLayout();
            //
            // button1
            //
            this.button1.Location = new System.Drawing.Point(84, 15);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(113, 45);
            this.button1.TabIndex = 0;
            this.button1.Text = "监听";
            this.button1.UseVisualStyleBackColor = true;
            this.button1.Click += new System.EventHandler(this.button1_Click);
            //
            // textBox1
            //
            this.textBox1.Location = new System.Drawing.Point(263, 28);
            this.textBox1.Name = "textBox1";
            this.textBox1.Size = new System.Drawing.Size(292, 21);
            this.textBox1.TabIndex = 1;
            //
            // linkLabel1
            //
            this.linkLabel1.Location = new System.Drawing.Point(144, 266);
            this.linkLabel1.Name = "linkLabel1";
            this.linkLabel1.Size = new System.Drawing.Size(440, 24);
            this.linkLabel1.TabIndex = 15;
            this.linkLabel1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            this.linkLabel1.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabel1_LinkClicked);
            //
            // button2
            //
            this.button2.Location = new System.Drawing.Point(498, 178);
            this.button2.Name = "button2";
            this.button2.Size = new System.Drawing.Size(80, 23);
            this.button2.TabIndex = 14;
            this.button2.Text = "浏览文件…";
            //
            // txtFileName
            //
            this.txtFileName.Location = new System.Drawing.Point(256, 178);
            this.txtFileName.Name = "txtFileName";
            this.txtFileName.Size = new System.Drawing.Size(232, 21);
            this.txtFileName.TabIndex = 12;
            //
            // label3
            //
            this.label3.AutoSize = true;
            this.label3.Font = new System.Drawing.Font("宋体", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
            this.label3.ForeColor = System.Drawing.Color.DarkBlue;
            this.label3.Location = new System.Drawing.Point(136, 184);
            this.label3.Name = "label3";
            this.label3.Size = new System.Drawing.Size(122, 12);
            this.label3.TabIndex = 13;
            this.label3.Text = "请输入上传文件名:";
            this.label3.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            //
            // txtServerPath
            //
            this.txtServerPath.Location = new System.Drawing.Point(256, 154);
            this.txtServerPath.Name = "txtServerPath";
            this.txtServerPath.Size = new System.Drawing.Size(320, 21);
            this.txtServerPath.TabIndex = 9;
            this.txtServerPath.Text = "http://www.x.com/WeUpload/";
            //
            // label2
            //
            this.label2.AutoSize = true;
            this.label2.Font = new System.Drawing.Font("宋体", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
            this.label2.ForeColor = System.Drawing.Color.Navy;
            this.label2.Location = new System.Drawing.Point(136, 158);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(122, 12);
            this.label2.TabIndex = 10;
            this.label2.Text = "请输入服务器地址:";
            this.label2.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            //
            // button3
            //
            this.button3.Location = new System.Drawing.Point(320, 210);
            this.button3.Name = "button3";
            this.button3.Size = new System.Drawing.Size(75, 23);
            this.button3.TabIndex = 11;
            this.button3.Text = "上载文件";
            this.button3.Click += new System.EventHandler(this.button3_Click);
            this.button3.MouseDown += new System.Windows.Forms.MouseEventHandler(this.button3_MouseDown);
            //
            // label1
            //
            this.label1.ForeColor = System.Drawing.Color.Red;
            this.label1.Location = new System.Drawing.Point(136, 242);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(448, 16);
            this.label1.TabIndex = 8;
            this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            //
            // timer1
            //
            this.timer1.Enabled = true;
            this.timer1.Interval = 35000;
            this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
            //
            // pictureBox1
            //
            this.pictureBox1.Location = new System.Drawing.Point(387, 74);
            this.pictureBox1.Name = "pictureBox1";
            this.pictureBox1.Size = new System.Drawing.Size(100, 50);
            this.pictureBox1.TabIndex = 16;
            this.pictureBox1.TabStop = false;
            //
            // button4
            //
            this.button4.Location = new System.Drawing.Point(319, 266);
            this.button4.Name = "button4";
            this.button4.Size = new System.Drawing.Size(75, 23);
            this.button4.TabIndex = 17;
            this.button4.Text = "打水印";
            this.button4.UseVisualStyleBackColor = true;
            this.button4.Click += new System.EventHandler(this.button4_Click);
            //
            // Form1
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(662, 317);
            this.Controls.Add(this.button4);
            this.Controls.Add(this.pictureBox1);
            this.Controls.Add(this.linkLabel1);
            this.Controls.Add(this.button2);
            this.Controls.Add(this.txtFileName);
            this.Controls.Add(this.label3);
            this.Controls.Add(this.txtServerPath);
            this.Controls.Add(this.label2);
            this.Controls.Add(this.button3);
            this.Controls.Add(this.label1);
            this.Controls.Add(this.textBox1);
            this.Controls.Add(this.button1);
            this.Name = "Form1";
            this.Text = "Form1";
            this.Resize += new System.EventHandler(this.Form1_Resize);
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.Button button1;
        private System.Windows.Forms.TextBox textBox1;
        private System.Windows.Forms.LinkLabel linkLabel1;
        private System.Windows.Forms.Button button2;
        private System.Windows.Forms.TextBox txtFileName;
        private System.Windows.Forms.Label label3;
        private System.Windows.Forms.TextBox txtServerPath;
        private System.Windows.Forms.Label label2;
        private System.Windows.Forms.Button button3;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.Timer timer1;
        private System.Windows.Forms.PictureBox pictureBox1;
        private System.Windows.Forms.Button button4;

 

 

 

后台代码:

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


using System.Runtime.InteropServices;
using System.Net.Sockets;
using Microsoft.Win32;

    #region 上传图片到服务器
        private void button3_Click(object sender, EventArgs e)
        {
            // 需要注意的是:txtServerPath文件夹有匿名可写的权限。
            // 可以自己定义新文件名字
            if (txtFileName.Text.Trim() == "" || txtServerPath.Text.Trim() == "")
            {
                MessageBox.Show("请输入你要上载的文件名字!", "错误:", MessageBoxButtons.OK,
                                                                 MessageBoxIcon.Information);
            }
            else
            {
                /// 得到文件名,文件扩展名字,服务器路径
                string fileNamePath = txtFileName.Text.Trim();
                string uriString = txtServerPath.Text.Trim();
                string fileName = fileNamePath.Substring(fileNamePath.LastIndexOf("//") + 1);
                string fileNameExt = fileName.Substring(fileName.LastIndexOf(".") + 1);
                if (uriString.EndsWith("/") == false) uriString = uriString + "/";

                uriString = uriString + fileName;
                /// 创建WebClient实例
                WebClient myWebClient = new WebClient();
                myWebClient.Credentials = CredentialCache.DefaultCredentials;

                // 要上传的文件
                FileStream fs = new FileStream(this.txtFileName.Text, FileMode.Open, FileAccess.Read);
                //FileStream fs = OpenFile();
                BinaryReader r = new BinaryReader(fs);
                try
                {
                    //使用UploadFile方法可以用下面的格式
                    //myWebClient.UploadFile(uriString,"PUT",fileNamePath);
                    byte[] postArray = r.ReadBytes((int)fs.Length);
                    Stream postStream = myWebClient.OpenWrite(uriString, "PUT");
                    if (postStream.CanWrite)
                    {
                        postStream.Write(postArray, 0, postArray.Length);
                        label1.Text = fileName + "上传成功!";
                    }
                    else
                    {
                        label1.Text = "文件目前不可写!";
                    }
                    postStream.Close();
                    linkLabel1.Text = "查看上载的文件";
                    for (int i = linkLabel1.Links.Count - 1; i > -1; i--)
                        linkLabel1.Links.Remove(linkLabel1.Links[i]);
                    linkLabel1.Links.Add(0, linkLabel1.Text.Length, uriString);
                }
                catch (WebException errMsg)
                {
                    label1.Text = "上传失败:" + errMsg.Message;
                }
            }
        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            this.WindowState = FormWindowState.Minimized;
            this.linkLabel1.Links[linkLabel1.Links.IndexOf(e.Link)].Visited = true;
            string target = e.Link.LinkData as string;
            if (null != target)
            {
                System.Diagnostics.Process.Start(target);
            }
            else
            {
                MessageBox.Show("请用浏览器访问:" + target);
            }
        }

        private void Form1_Resize(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Maximized) this.WindowState = FormWindowState.Normal;
        }

        private void button3_MouseDown(object sender, MouseEventArgs e)
        {
            if (txtFileName.Text.Trim() != "" && txtServerPath.Text.Trim() != "")
                label1.Text = "正在上传文件,请稍侯……!";
        }
        #endregion

作者: Leo_wl

    

出处: http://www.cnblogs.com/Leo_wl/

    

本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

版权信息

查看更多关于winform如何上传图片到服务器的详细内容...

  阅读:41次