C# 通過WebService方式 IIS發布網站 上傳文件到服務器[轉]


http://blog.sina.com.cn/s/blog_517cae3c0102v0y7.html

應用場景:要將本地的文件 上傳到服務器的虛擬機上

C# <wbr>通過WebService方式 <wbr>IIS發布網站 <wbr>上傳文件到服務器 網絡環境:公司局域網(如下圖中第二種)

開發環境:VS2010  

服務器環境:WinServer2008    虛擬機環境:WinServer2008

 

我的程序結構目錄

AppSrvice 是服務文件 將來發布了以后要放到服務器上, WindowFormsAppp 是Winform程序

 

第一步:創建一個新的: Windows窗體應用程序

 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
//using System.Threading;
using System.Windows.Forms;
using System.Security.Cryptography;
using System.IO;
using System.Web.Services;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

     

        private void button1_Click(object sender, EventArgs e)
        {
            //localhost.WebService1 client = new localhost.WebService1();  
            WindowsFormsApp.ServiceReference1.Service1SoapClient client = new WindowsFormsApp.ServiceReference1.Service1SoapClient();
            //WindowsFormsApp.ServiceReference1.WebService1SoapClient client = new WindowsFormsApp.ServiceReference1.WebService1SoapClient();
            //上傳服務器后的文件名  一般不修改文件名稱  
            int start = textBox1.Text.LastIndexOf("\");
            int length = textBox1.Text.Length;
            string serverfile = textBox1.Text.Substring(start + 1, length - textBox1.Text.LastIndexOf("."))
                    + DateTime.Now.ToString("-yyyy-mm-dd-hh-mm-ss")
                    + textBox1.Text.Substring(textBox1.Text.LastIndexOf("."), textBox1.Text.Length - textBox1.Text.LastIndexOf("."));

            client.CreateFile(serverfile);
            //要上傳文件的路徑  
            string sourceFile = textBox1.Text;
            string md5 = GetMD5(sourceFile);

            FileStream fs = new FileStream(sourceFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            int size = (int)fs.Length;
            int bufferSize = 1024 * 512;
            int count = (int)Math.Ceiling((double)size / (double)bufferSize);
            for (int i = 0; i < count; i++)
            {
                int readSize = bufferSize;
                if (i == count - 1)
                    readSize = size - bufferSize * i;
                byte[] buffer = new byte[readSize];
                fs.Read(buffer, 0, readSize);
                client.Append(serverfile, buffer);
            }

            bool isVerify = client.Verify(serverfile, md5);
            if (isVerify)
                MessageBox.Show("上傳成功");
            else
                MessageBox.Show("上傳失敗");

        }

        private string GetMD5(string fileName)
        {
            FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
            MD5CryptoServiceProvider p = new MD5CryptoServiceProvider();
            byte[] md5buffer = p.ComputeHash(fs);
            fs.Close();
            string md5Str = "";
            List strList = new List();
            for (int i = 0; i < md5buffer.Length; i++)
            {
                md5Str += md5buffer[i].ToString("x2");
            }
            return md5Str;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            OpenFileDialog openDialog = new OpenFileDialog();
            //openDialog.Filter = "視頻文件(*.avi,*.wmv,*.mp4)|*.avi;*.wmv;*.mp4";
            if (openDialog.ShowDialog() == DialogResult.OK)
            {
                textBox1.Text = openDialog.FileName;
            }
        }
    }
}

第二步:創建WebService

關鍵代碼如下:

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using System.IO;
using System.Text;
using System.Security.Cryptography;
using System.Collections.Generic;
namespace WebService1
{
    ///
    /// Service1 的摘要說明
    ///
    [WebService(Namespace = " http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [ToolboxItem(false)]
    // 若要允許使用 ASP.NET AJAX 從腳本中調用此 Web 服務,請取消對下行的注釋。
    // [System.Web.Script.Services.ScriptService]
    public class Service1 : System.Web.Services.WebService
    {
         
        [WebMethod]
        public string HelloWorld()
        {
            return "Hello World";
        }
        [WebMethod]
        public bool CreateFile(string fileName)
        {
            bool isCreate = true;
            try
            {
                fileName = Path.Combine(Server.MapPath(""), Path.GetFileName(fileName));
                //首先設置上傳服務器文件的路徑  然后發布web服務 發布的時候要自己建一個自己知道的文件夾 "C:\NMGIS_Video" "C:\NMGIS_Video"                fileName = Path.Combine(Server.MapPath("") + @"\Video" + Path.GetFileName(fileName));  
                FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);
                fs.Close();
            }
            catch
            {
                isCreate = false;
            }
            return isCreate;
        }
        [WebMethod]
        public bool Append(string fileName, byte[] buffer)
        {
            bool isAppend = true;
            try
            {
                //fileName = Path.Combine(@"C:\NMGIS_Video" + Path.GetFileName(fileName));  
                fileName = Path.Combine(Server.MapPath(""), Path.GetFileName(fileName));
                FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
                fs.Seek(0, SeekOrigin.End);
                fs.Write(buffer, 0, buffer.Length);
                fs.Close();
            }
            catch
            {
                isAppend = false;
            }
            return isAppend;
        }
        [WebMethod]
        public bool Verify(string fileName, string md5)
        {
            bool isVerify = true;
            try
            {
                fileName = Path.Combine(Server.MapPath(""), Path.GetFileName(fileName));

                // fileName = Server.MapPath("D:\MesWebCR\picture")  + Path.GetFileName(fileName);
                FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
                MD5CryptoServiceProvider p = new MD5CryptoServiceProvider();
                byte[] md5buffer = p.ComputeHash(fs);
                fs.Close();
                string md5Str = "";
                List strList = new List();
                for (int i = 0; i < md5buffer.Length; i++)
                {
                    md5Str += md5buffer[i].ToString("x2");
                }
                if (md5 != md5Str)
                    isVerify = false;
            }
            catch
            {
                isVerify = false;
            }
            return isVerify;
        }
 
    }
}
 
 

第三步:發布服務

選中服務項目,右鍵 發布

 

發布方法選擇:文件系統

目標位置:是選擇你發布后生成文件的位置 自己隨便找個地方即可

然后點擊 發布

 

第四步:拷貝文件到服務器

將剛才發布好的文件拷貝到你要上傳到的服務器的虛擬機的指定目錄下

 

 

第五步:在虛擬機上發布網站

打開虛擬機的IIS 發布一個網站 文件路徑指向你剛才拷貝到虛擬機上的文件目錄

IP地址就是當前虛擬機的IP  要設置為固定的IP

端口一定注意 不要與當前正在使用的端口沖突 建議更改一個

然后確定 發布網站

 

 

選中剛才發布的網站 ,右邊滾動條向下,選擇 默認文檔並雙擊

 

雙擊打開后右邊點擊添加按鈕 ,當剛才復制到虛擬機當中的 .asmx 文件名添加到里邊點確定

 

網站右鍵 ,管理網站,瀏覽  查看發不好的網站是否可以訪問

 

我這里瀏覽是可以訪問的:如下圖

 

第六步:設置虛擬機網絡環境

虛擬機》編輯  或者  開始菜單中 找到 Virtral Network Editor

 

打開虛擬網絡編輯器

 

Nat 設置里邊 映射兩個端口  TCP、UDP類型各一個, 然后點擊確定

宿主機的8070 端口映射到虛擬機的“192.168.16.135”的8070端口了,因為web服務自動開放的端口是8070,所以,只要我們訪問 “http://192.168.1.54:8070”,就可以訪問到虛擬機的8070端口,也就是web服務了(這里宿主機的端口可以改成其他端口,無需跟虛擬機端口一致,我是為了省事都寫成了8070)

 

然后點擊應用 確定  。。。這里設置好了以后就可以通過訪問虛擬機的宿主機IP訪問到你虛擬機上的服務

 

 此時就可以通過其他任意機器訪問你的.asmx頁面 注意你的端口一定要正確正如上面所說:這里直接通過訪問宿主機的Ip就可以

 

第七步:為客戶端添加服務器引用

 項目右鍵 添加服務引用

 

添加服務地址 點擊 前往 ,如果正確的話 會在下面顯示出你的服務頁面 然后點擊確定

 

 第八步:測試

運行客戶端測試

 

這里顯示成功了  那么我們去虛擬機的目錄下看一看到底有沒有

 

這里有兩個文件 我測試了兩次 ,  文件名稱我在程序當中追加了當前時間的格式化字符串,文件大小也是對的。

免積分 源碼下載 地址:http://download.csdn.net/detail/u010011052/7213805


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM