- 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
上传文件到服务器
最新推荐文章于 2024-08-06 23:51:16 发布