• 推荐
  • 评论
  • 收藏

winform如何上传图片到服务器

2022-12-07    6117次浏览

有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/

  如果想要利用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,相关代码:

  1. <%@ WebHandler Language="C#" Class="Uploader" %>  
  2. using System;  
  3. using System.IO;  
  4. using System.Web;  
  5.   
  6. public class Uploader : IHttpHandler  
  7. {  
  8.     public void ProcessRequest(HttpContext hc)  
  9.     {  
  10.         foreach (string fileKey in hc.Request.Files)  
  11.         {  
  12.             HttpPostedFile file = hc.Request.Files[fileKey];  
  13.             file.SaveAs(Path.Combine(hc.Server.MapPath("."), file.FileName));  
  14.         }  
  15.     }  
  16.   
  17.     public bool IsReusable  
  18.     {  
  19.         get { return true; }  
  20.     }  
  21. }  

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

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

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


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

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

  1. <%@ WebHandler Language="C#" Class="Uploader" %>  
  2. using System;  
  3. using System.IO;  
  4. using System.Web;  
  5.   
  6. public class Uploader : IHttpHandler  
  7. {  
  8.     public void ProcessRequest(HttpContext hc)  
  9.     {  
  10.         string NowPath = Path.Combine(hc.Server.MapPath("."), hc.Request["path"]);  
  11.   
  12.         if (!Directory.Exists(NowPath))  
  13.         {  
  14.             Directory.CreateDirectory(NowPath);  
  15.         }  
  16.   
  17.         foreach (string fileKey in hc.Request.Files)  
  18.         {  
  19.             HttpPostedFile file = hc.Request.Files[fileKey];  
  20.             string FilePath = Path.Combine(NowPath, file.FileName);  
  21.             if (File.Exists(FilePath))  
  22.             {  
  23.                 if (Convert.ToBoolean(hc.Request["overwrite"]))  
  24.                 {  
  25.                     File.Delete(FilePath);  
  26.                 }  
  27.                 else  
  28.                 {  
  29.                     continue;  
  30.                 }  
  31.             }  
  32.             file.SaveAs(FilePath);  
  33.         }  
  34.     }  
  35.   
  36.     public bool IsReusable  
  37.     {  
  38.         get { return true; }  
  39.     }  
  40. }  

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

  1. string url = @"http://www.yongfa365.com/Uploader.ashx?Overwrite=true&PATH=Logs\" + DateTime.Now.ToString("yyyy-MM-dd");  
  2. foreach (string file in Directory.GetFiles(item))  
  3. {  
  4.     System.Net.WebClient myWebClient = new System.Net.WebClient();  
  5.     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
原文地址:https://www.cnblogs.com/Leo_wl/p/2107724.html