客戶端:先創建一個winform窗體的應用程序項目
項目結構
winform窗體布局分配好,需要一個文本框,兩個按鈕,一個進度條,幾個label標簽
具體如下:
客戶端代碼如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace UpFileClient
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
string filePath = "";
private void btnSelect_Click(object sender, EventArgs e)
{
//創建文件彈出選擇窗口(包括文件名)對象
OpenFileDialog ofd = new OpenFileDialog();
//判斷選擇的路徑
if (ofd.ShowDialog() == DialogResult.OK)
{
this.txtSoundPath.Text = ofd.FileName.ToString();
}
filePath = this.txtSoundPath.Text;
}
private void btnUpSound_Click(object sender, EventArgs e)
{
try {
//上傳服務器的地址(web服務)
string address = "http://localhost:28207/WebService/SaveFileWebForm.aspx";
//上傳后文件保存的名稱
string saveName = DateTime.Now.ToString("yyyyMMddHHmmss");
int count = UpSound_Request(address, filePath, saveName, this.progressBar1);
if (count > 0)
{
MessageBox.Show("上傳文件成功!");
}
else
{
MessageBox.Show("上傳文件失敗!");
}
}catch(Exception ex){
MessageBox.Show(""+ex.GetBaseException());
}
}
/// <summary>
/// 上傳錄音文件
/// </summary>
/// <param name="address">文件上傳到服務器的路徑</param>
/// <param name="fileNamePath">要上傳的本地路徑(全路徑)</param>
/// <param name="saveName">文件上傳后的名稱</param>
/// <returns>成功返回1,失敗返回2</returns>
public int UpSound_Request(string address, string fileNamePath, string saveName, ProgressBar progressBar)
{
int returnValue = 0;
//要上傳的文件
FileStream fs = new FileStream(fileNamePath, FileMode.Open, FileAccess.Read);
//二進制對象
BinaryReader r = new BinaryReader(fs);
//時間戳
string strBoundary = "----------" + DateTime.Now.Ticks.ToString("x");
byte[] boundaryBytes = Encoding.ASCII.GetBytes("\r\n--" + strBoundary + "\r\n");
//請求的頭部信息
StringBuilder sb = new StringBuilder();
sb.Append("--");
sb.Append(strBoundary);
sb.Append("\r\n");
sb.Append("Content-Disposition: form-data; name=\"");
sb.Append("file");
sb.Append("\"; filename=\"");
sb.Append(saveName);
sb.Append("\";");
sb.Append("\r\n");
sb.Append("Content-Type: ");
sb.Append("application/octet-stream");
sb.Append("\r\n");
sb.Append("\r\n");
string strPostHeader = sb.ToString();
byte[] postHeaderBytes = Encoding.UTF8.GetBytes(strPostHeader);
// 根據uri創建HttpWebRequest對象
HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(new Uri(address));
httpReq.Method = "POST";
//對發送的數據不使用緩存
httpReq.AllowWriteStreamBuffering = false;
//設置獲得響應的超時時間(300秒)
httpReq.Timeout = 300000;
httpReq.ContentType = "multipart/form-data; boundary=" + strBoundary;
long length = fs.Length + postHeaderBytes.Length + boundaryBytes.Length;
long fileLength = fs.Length;
httpReq.ContentLength = length;
try
{
progressBar.Maximum = int.MaxValue;
progressBar.Minimum = 0;
progressBar.Value = 0;
//每次上傳4k
int bufferLength = 4096;
byte[] buffer = new byte[bufferLength]; //已上傳的字節數
long offset = 0; //開始上傳時間
DateTime startTime = DateTime.Now;
int size = r.Read(buffer, 0, bufferLength);
Stream postStream = httpReq.GetRequestStream(); //發送請求頭部消息
postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
while (size > 0)
{
postStream.Write(buffer, 0, size);
offset += size;
progressBar.Value = (int)(offset * (int.MaxValue / length));
TimeSpan span = DateTime.Now - startTime;
double second = span.TotalSeconds;
labTime.Text = "已用時:" + second.ToString("F2") + "秒";
if (second > 0.001)
{
labSpeed.Text = "平均速度:" + (offset / 1024 / second).ToString("0.00") + "KB/秒";
}
else
{
labSpeed.Text = " 正在連接…";
}
labState.Text = "已上傳:" + (offset * 100.0 / length).ToString("F2") + "%";
labSize.Text = (offset / 1048576.0).ToString("F2") + "M/" + (fileLength / 1048576.0).ToString("F2") + "M";
Application.DoEvents();
size = r.Read(buffer, 0, bufferLength);
}
//添加尾部的時間戳
postStream.Write(boundaryBytes, 0, boundaryBytes.Length);
postStream.Close();
//獲取服務器端的響應
WebResponse webRespon = httpReq.GetResponse();
Stream s = webRespon.GetResponseStream();
//讀取服務器端返回的消息
StreamReader sr = new StreamReader(s);
String sReturnString = sr.ReadLine();
s.Close();
sr.Close();
if (sReturnString == "Success")
{
returnValue = 1;
}
else if (sReturnString == "Error")
{
returnValue = 0;
}
}
catch
{
returnValue = 0;
}
finally
{
fs.Close();
r.Close();
}
return returnValue;
}
}
}
客戶端上傳文件的效果圖:
服務器端:
創建一個web mvc4項目,在創建一個webservice文件夾,在文件夾下創建一個SaveFileWebForm.axpx接口,
設置這個頁面為項目起始頁,打開這個頁面,右鍵查看代碼,編寫服務器端代碼,運行項目
項目結構:
客戶端上傳文件時,服務器端(SaveFileWebForm.axpx)需要訪問的到,(注:先運行服務器程序項目,在運行客戶端程序項目)
服務器端源碼:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace SaveFileWebService.WebService
{
public partial class SaveFileWebForm : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Request.Files.Count > 0)
{
try
{
//得到客戶端上傳的文件
HttpPostedFile file = Request.Files[0];
//服務器端要保存的路徑
string filePath = "D:\\Test\\" + file.FileName + ".mp3";
file.SaveAs(filePath);
//返回結果
Response.Write("Success");
}
catch
{
Response.Write("Error");
}
}
else
{
Response.Write("Error1");
}
}
}
}
服務器接收后文件如下圖:
PS: 客戶端上傳文件到服務器端的demo下載地址:http://pan.baidu.com/s/1nuSP3c9