新建->項目->ASP.NET Web服務應用程序
//Service.cs
public class Service : System.Web.Services.WebService
{
public Service () {
//如果使用設計的組件,請取消註釋以下行
//InitializeComponent();
}
//[WebMethod]
//public string HelloWorld() {
// return "Hello World";
//}
[WebMethod]
public int UploadFile(string fileName, int Length, byte[] file_data)
{ //上傳二進制文件
string constr = "server=127.0.0.1;database=tb_file;Integrated Security=SSPI;";
SqlCommand cmd = new SqlCommand();
SqlConnection con = new SqlConnection(constr);
//連接數據庫
cmd.Connection = con;
//獲取或設置一個值,該值指示如何解釋 CommandText 屬性,CommandType.Text指SQL 文本命令
cmd.CommandType = CommandType.Text;
//連接打開
if (con.State == 0)
con.Open();
cmd.CommandText = "insert into tb_file (filename,filesize,filedata) values( @filename, @filesize, @filedata)";
SqlParameter spFilename = new SqlParameter("@filename", SqlDbType.VarChar);
spFilename.Value = fileName;
cmd.Parameters.Add(spFilename);
SqlParameter spFile = new SqlParameter("@filedata", SqlDbType.VarBinary);//SqlDbType.VarBinary:Byte 類型的 Array。二進制數據的可變長度流,範圍在 1 到 8,000 個字節之間。如果字節數組大於 8,000 個字節,隱式轉換會失敗。在使用比 8,000 個字節大的字節數組時,請顯式設置對象。
spFile.Value = file_data;
cmd.Parameters.Add(spFile);
SqlParameter spFilesz = new SqlParameter("@filesize", SqlDbType.Int);
spFilesz.Value = Length;
cmd.Parameters.Add(spFilesz);
//執行前面構造的sql查詢命令
int count = cmd.ExecuteNonQuery();
//服務器收到客戶端發送的這個數據以後,先保存在數據庫中,,然後順便在本地保存一個副本
string str_SavePath = "F:\C#學習作業、\WebClient\";
FileStream newfs = new FileStream(str_SavePath + fileName, FileMode.Create, FileAccess.Write);
newfs.Write(file_data, 0, Length);