国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 學(xué)院 > 開(kāi)發(fā)設(shè)計(jì) > 正文

借助WebService實(shí)現(xiàn)多線程上傳文件

2019-11-17 04:27:30
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

  在WebService的幫助下,進(jìn)行多線程上傳文件是非常簡(jiǎn)單。因此我只做個(gè)簡(jiǎn)單的例子,那么如果想要實(shí)現(xiàn)此功能的朋友,可以在我的基礎(chǔ)上進(jìn)行擴(kuò)展。

  首先說(shuō)說(shuō)服務(wù)器端,只需要提供一個(gè)能允許多線程寫(xiě)文件的函數(shù)即可,具體代碼如下。view plaincopy to clipboardPRint?
[WebMethod]  
 
public bool UploadFileData( string FileName, int StartPosition, byte[] bData )  
 
{  
 
 string strFullName = Server.MapPath( "Uploads" ) + @"/" + FileName; 
 
 FileStream fs = null; 
 
 try 
 
 { 
 
 fs = new FileStream( strFullName, FileMode.OpenOrCreate,  
 
 Fileaccess.Write, FileShare.Write ); 
 
 } 
 
 catch( IOException err ) 
 
 { 
 
 session["ErrorMessage"] = err.Message;  
 
 return false;  
 
 }  
 
   
 
 using( fs )  
 
 {  
 
 fs.Position = StartPosition;  
 
 fs.Write( bData, 0, bData.Length );  
 
 }  
 
 return true;  
 

[WebMethod]

public bool UploadFileData( string FileName, int StartPosition, byte[] bData )

{

 string strFullName = Server.MapPath( "Uploads" ) + @"/" + FileName;

 FileStream fs = null;

 try

 {

 fs = new FileStream( strFullName, FileMode.OpenOrCreate,

 FileAccess.Write, FileShare.Write );

 }

 catch( IOException err )

 {

 Session["ErrorMessage"] = err.Message;

 return false;

 }

 

 using( fs )

 {

 fs.Position = StartPosition;

 fs.Write( bData, 0, bData.Length );

 }

 return true;

}  其中“Uploads”是在服務(wù)程序所在目錄下的一個(gè)子目錄,需要設(shè)置aspNET用戶對(duì)此目錄具有可寫(xiě)權(quán)限。
  相對(duì)于服務(wù)器端來(lái)說(shuō),客戶端要稍微復(fù)雜一些,因?yàn)橐獱砍兜蕉嗑€程的問(wèn)題。為了更好的傳遞參數(shù),我用一個(gè)線程類(lèi)來(lái)完成。具體如下。view plaincopy to clipboardprint?
public delegate void UploadFileData( string FileName, int StartPos, byte[] bData );  
 
 
 
/// <summary>  
 
/// FileThread: a class for sub-thread  
 
/// </summary>  
 
sealed class FileThread  
 
{  
 
private int nStartPos;  
 
private int nTotalBytes;  
 
private string strFileName;  
 
public static UploadFileData UploadHandle;  
 
 
 
/// <summary>  
 
/// Constructor  
 
/// </summary>  
 
/// <param name="StartPos"></param>  
 
/// <param name="TotalBytes"></param>  
 
/// <param name="FileName"></param>  
 
public FileThread( int StartPos, int TotalBytes, string FileName )  
 
{  
 
//Init thread variant  
 
nStartPos = StartPos;  
 
nTotalBytes = TotalBytes;  
 
strFileName = FileName;  
 
 
 
//Only for debug  
 
Debug.WriteLine( string.Format( "File name:{0} position: {1} total byte:{2}",  
 
strFileName, nStartPos, nTotalBytes ) );  
 
}  
 
 
 
/// <summary>  
 
/// Sub-thread entry function   
 
/// </summary>  
 
/// <param name="stateinfo"></param>  
 
public void UploadFile( object stateinfo )  
 
{  
 
int nRealRead, nBufferSize;  
 
const int BUFFER_SIZE = 10240;  
 
 
 
using( FileStream fs = new FileStream( strFileName,  
 
FileMode.Open, FileAccess.Read,  
 
FileShare.Read ) )  
 
{  
 
string sName = strFileName.Substring( strFileName.LastIndexOf( "http://" ) + 1 );  
 
byte[] bBuffer = new byte[BUFFER_SIZE];//Init 10k buffer  
 
fs.Position = nStartPos;  
 
nRealRead = 0;  
 
do 
 
{  
 
nBufferSize = BUFFER_SIZE;  
 
if( nRealRead + BUFFER_SIZE > nTotalBytes )  
 
nBufferSize = nTotalBytes - nRealRead;  
 
 
 
nBufferSize = fs.Read( bBuffer, 0, nBufferSize );  
 
if( nBufferSize == BUFFER_SIZE )  
 
UploadHandle( sName,  
 
nRealRead + nStartPos,  
 
bBuffer );  
 
else if( nBufferSize > 0 )  
 
{  
 
//Copy data   
 
byte[] bytData = new byte[nBufferSize];  
 
Array.Copy( bBuffer,0, bytData, 0, nBufferSize );  
 
 
 
UploadHandle( sName,  
 
nRealRead + nStartPos,  
 
bytData );  
 
}  
 
 
 
nRealRead += nBufferSize;  
 
}  
 
while( nRealRead < nTotalBytes );  
 
}  
 
//Release signal  
 
ManualResetEvent mr = stateinfo as ManualResetEvent;  
 
if( mr != null )  
 
mr.Set();  
 
}  
 

 public delegate void UploadFileData( string FileName, int StartPos, byte[] bData );

 

 /// <summary>

 /// FileThread: a class for sub-thread

 /// </summary>

 sealed class FileThread

 {

 private int nStartPos;

 private int nTotalBytes;

 private string strFileName;

 public static UploadFileData UploadHandle;

 

 /// <summary>

 /// Constructor

 /// </summary>

 /// <param name="StartPos"></param>

 /// <param name="TotalBytes"></param>

 /// <param name="FileName"></param>

 public FileThread( int StartPos, int TotalBytes, string FileName )

 {

 //Init thread variant

 nStartPos = StartPos;

 nTotalBytes = TotalBytes;

 strFileName = FileName;

 

 //Only for debug

 Debug.WriteLine( string.Format( "File name:{0} position: {1} total byte:{2}",

 strFileName, nStartPos, nTotalBytes ) );

 }

 

 /// <summary>

 /// Sub-thread entry function

 /// </summary>

 /// <param name="stateinfo"></param>

 public void UploadFile( object stateinfo )

 {

 int nRealRead, nBufferSize;

 const int BUFFER_SIZE = 10240;

 

 using( FileStream fs = new FileStream( strFileName,

 FileMode.Open, FileAccess.Read,

 FileShare.Read ) )

 {

 string sName = strFileName.Substring( strFileName.LastIndexOf( "http://" ) + 1 );

 byte[] bBuffer = new byte[BUFFER_SIZE];//Init 10k buffer

 fs.Position = nStartPos;

 nRealRead = 0;

 do

 {

 nBufferSize = BUFFER_SIZE;

 if( nRealRead + BUFFER_SIZE > nTotalBytes )

 nBufferSize = nTotalBytes - nRealRead;

 

 nBufferSize = fs.Read( bBuffer, 0, nBufferSize );

 if( nBufferSize == BUFFER_SIZE )

 UploadHandle( sName,

 nRealRead + nStartPos,

 bBuffer );

 else if( nBufferSize > 0 )

 {

 //Copy data

 byte[] bytData = new byte[nBufferSize];

 Array.Copy( bBuffer,0, bytData, 0, nBufferSize );

 

 UploadHandle( sName,

 nRealRead + nStartPos,

 bytData );

 }

 

 nRealRead += nBufferSize;

 }

 while( nRealRead < nTotalBytes );

 }

 //Release signal

 ManualResetEvent mr = stateinfo as ManualResetEvent;

 if( mr != null )

 mr.Set();

 }

 }  那么在執(zhí)行的時(shí)候,要?jiǎng)?chuàng)建線程類(lèi)對(duì)象,并為每一個(gè)每個(gè)線程設(shè)置一個(gè)信號(hào)量,從而能在所有線程都結(jié)束的時(shí)候得到通知,大致的代碼如下。view plaincopy to clipboardprint?
FileInfo fi = new FileInfo( txtFileName.Text );  
 
if( fi.Exists )  
 
{  
 
btnUpload.Enabled = false;//Avoid upload twice  
 
 
 
//Init signals  
 
ManualResetEvent[] events = new ManualResetEvent[5];  
 
 
 
//Devide blocks  
 
int nTotalBytes = (int)( fi.Length / 5 );  
 
for( int i = 0; i < 5; i++ )  
 
{  
 
events[i] = new ManualResetEvent( false );  
 
FileThread thdSub = new FileThread(   
 
i * nTotalBytes,  
 
( fi.Length - i * nTotalBytes ) > nTotalBytes ? nTotalBytes:(int)( fi.Length - i * nTotalBytes ),  
 
fi.FullName );  
 
ThreadPool.QueueUserWorkItem( new WaitCallback( thdSub.UploadFile ), events[i] );  
 
}  
 
 
 
//Wait for threads finished  
 
WaitHandle.WaitAll( events );  
 
 
 
//Reset button status  
 
btnUpload.Enabled = true;  
 

 FileInfo fi = new FileInfo( txtFileName.Text );

 if( fi.Exists )

 {

 btnUpload.Enabled = false;//Avoid upload twice

 

 //Init signals

 ManualResetEvent[] events = new ManualResetEvent[5];

 

 //Devide blocks

 int nTotalBytes = (int)( fi.Length / 5 );

 for( int i = 0; i < 5; i++ )

 {

 events[i] = new ManualResetEvent( false );

 FileThread thdSub = new FileThread(

 i * nTotalBytes,

 ( fi.Length - i * nTotalBytes ) > nTotalBytes ? nTotalBytes:(int)( fi.Length - i * nTotalBytes ),

 fi.FullName );

 ThreadPool.QueueUserWorkItem( new WaitCallback( thdSub.UploadFile ), events[i] );

 }

 

 //Wait for threads finished

 WaitHandle.WaitAll( events );

 

 //Reset button status

 btnUpload.Enabled = true;

 }  總體來(lái)說(shuō),程序還是相對(duì)比較簡(jiǎn)單,而我也只是做了個(gè)簡(jiǎn)單例子而已,一些細(xì)節(jié)都沒(méi)有進(jìn)行處理。
  如下是客戶端的完整代碼。view plaincopy to clipboardprint?
//--------------------------- Multi-thread Upload Demo ---------------------------------------  
 
//--------------------------------------------------------------------------------------------  
 
//---File:          frmUpload  
 
//---Description:   The multi-thread upload form file to demenstrate howto use multi-thread to   
 
//                  upload files  
 
//---Author:        Knight  
 
//---Date:          Oct.12, 2006  
 
//--------------------------------------------------------------------------------------------  
 
//---------------------------{Multi-thread Upload Demo}---------------------------------------  
 
using System;  
 
using System.Drawing;  
 
using System.Collections;  
 
using System.ComponentModel;  
 
using System.Windows.Forms;  
 
using System.Data;  
 
   
 
namespace CSUpload  
 
{  
 
 using System.IO;  
 
 using System.Diagnostics;  
 
 using System.Threading;  
 
 using WSUploadFile;//Web-service reference namespace  
 
   
 
 /// <summary>  
 
 /// Summary description for Form1.  
 
 /// </summary>  
 
 public class frmUpload : System.Windows.Forms.Form  
 
 {  
 
 private System.Windows.Forms.TextBox txtFileName;  
 
 private System.Windows.Forms.Button btnBrowse;  
 
 private System.Windows.Forms.Button btnUpload;  
 
 /// <summary>  
 
 /// Required designer variable.  
 
 /// </summary>  
 
 private System.ComponentModel.Container components = null;  
 
   
 
 public frmUpload()  
 
 {  
 
 //  
 
 // Required for Windows Form Designer support  
 
 //  
 
 InitializeComponent();  
 
   
 
 //  
 
 // TODO: Add any constructor code after InitializeComponent call  
 
 //  
 
 }  
 
   
 
 /// <summary>  
 
 /// Clean up any resources being used.  
 
 /// </summary>  
 
 protected override void Dispose( bool disposing )  
 
 {  
 
 if( disposing )  
 
 {  
 
 if (components != null)   
 
 {  
 
 components.Dispose();  
 
 }  
 
 }  
 
 base.Dispose( disposing );  
 
 } 
 
  
 
 #region Windows Form Designer generated code  
 
 /// <summary>  
 
 /// Required method for Designer support - do not modify  
 
 /// the contents of this method with the code editor.  
 
 /// </summary>  
 
 private void InitializeComponent()  
 
 {  
 
 this.txtFileName = new System.Windows.Forms.TextBox();  
 
 this.btnBrowse = new System.Windows.Forms.Button();  
 
 this.btnUpload = new System.Windows.Forms.Button();  
 
 this.SuspendLayout();  
 
 //   
 
 // txtFileName  
 
 //   
 
 this.txtFileName.Location = new System.Drawing.Point(16, 24);  
 
 this.txtFileName.Name = "txtFileName";  
 
 this.txtFileName.Size = new System.Drawing.Size(248, 20);  
 
 this.txtFileName.TabIndex = 0;  
 
 this.txtFileName.Text = "";  
 
 //   
 
 // btnBrowse  
 
 //   
 
 this.btnBrowse.Location = new System.Drawing.Point(272, 24);  
 
 this.btnBrowse.Name = "btnBrowse";  
 
 this.btnBrowse.TabIndex = 1;  
 
 this.btnBrowse.Text = "&Browse...";  
 
 this.btnBrowse.Click += new System.EventHandler(this.btnBrowse_Click);  
 
 //   
 
 // btnUpload  
 
 //   
 
 this.btnUpload.Location = new System.Drawing.Point(272, 56);  
 
 this.btnUpload.Name = "btnUpload";  
 
 this.btnUpload.TabIndex = 2;  
 
 this.btnUpload.Text = "&Upload";  
 
 this.btnUpload.Click += new System.EventHandler(this.btnUpload_Click);  
 
 //   
 
 // frmUpload  
 
 //   
 
 this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);  
 
 this.ClientSize = new System.Drawing.Size(370, 111);  
 
 this.Controls.Add(this.btnUpload);  
 
 this.Controls.Add(this.btnBrowse);  
 
 this.Controls.Add(this.txtFileName);  
 
 this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;  
 
 this.MaximizeBox = false;  
 
 this.Name = "frmUpload";  
 
 this.Text = "Upload";  
 
 this.Load += new System.EventHandler(this.frmUpload_Load);  
 
 this.ResumeLayout(false);  
 
   
 
 } 
 
 #endregion  
 
   
 
 /// <summary>  
 
 /// The main entry point for the application.  
 
 /// </summary>  
 
 static void Main()   
 
 {  
 
 Application.Run(new frmUpload());  
 
 }  
 
   
 
 private FileUpload myUpload = new FileUpload();  
 
 private void UploadData( string FileName, int StartPos, byte[] bData )  
 
 {  
 
 //Call web service upload  
 
 myUpload.UploadFileData( FileName, StartPos, bData );  
 
 }  
 
   
 
 private void btnUpload_Click(object sender, System.EventArgs e)  
 
 {  
 
 FileInfo fi = new FileInfo( txtFileName.Text );  
 
 if( fi.Exists )  
 
 {  
 
 btnUpload.Enabled = false;//Avoid upload twice  
 
   
 
 //Init signals  
 
 ManualResetEvent[] events = new ManualResetEvent[5];  
 
   
 
 //Devide blocks  
 
 int nTotalBytes = (int)( fi.Length / 5 );  
 
 for( int i = 0; i < 5; i++ )  
 
 {  
 
 events[i] = new ManualResetEvent( false );  
 
 FileThread thdSub = new FileThread(   
 
 i * nTotalBytes,  
 
 ( fi.Length - i * nTotalBytes ) > nTotalBytes ? nTotalBytes:(int)( fi.Length - i * nTotalBytes ),  
 
 fi.FullName );  
 
 ThreadPool.QueueUserWorkItem( new WaitCallback( thdSub.UploadFile ), events[i] );  
 
 }  
 
   
 
 //Wait for threads finished  
 
 WaitHandle.WaitAll( events );  
 
   
 
 //Reset button status  
 
 btnUpload.Enabled = true;  
 
 }  
 
   
 
 }  
 
   
 
 private void frmUpload_Load(object sender, System.EventArgs e)  
 
 {  
 
 FileThread.UploadHandle = new UploadFileData( this.UploadData );  
 
 }  
 
   
 
 private void btnBrowse_Click(object sender, System.EventArgs e)  
 
 {  
 
 if( fileOpen.ShowDialog() == DialogResult.OK )  
 
 txtFileName.Text = fileOpen.FileName;  
 
 }  
 
 private OpenFileDialog fileOpen = new OpenFileDialog();  
 
   
 
   
 
 }  
 
   
 
 public delegate void UploadFileData( string FileName, int StartPos, byte[] bData );  
 
   
 
 /// <summary>  
 
 /// FileThread: a class for sub-thread  
 
 /// </summary>  
 
 sealed class FileThread  
 
 {  
 
 private int nStartPos;  
 
 private int nTotalBytes;  
 
 private string strFileName;  
 
 public static UploadFileData UploadHandle;  
 
   
 
 /// <summary>  
 
 /// Constructor  
 
 /// </summary>  
 
 /// <param name="StartPos"></param>  
 
 /// <param name="TotalBytes"></param>  
 
 /// <param name="FileName"></param>  
 
 public FileThread( int StartPos, int TotalBytes, string FileName )  
 
 {  
 
 //Init thread variant  
 
 nStartPos = StartPos;  
 
 nTotalBytes = TotalBytes;  
 
 strFileName = FileName;  
 
   
 
 //Only for debug  
 
 Debug.WriteLine( string.Format( "File name:{0} position: {1} total byte:{2}",  
 
 strFileName, nStartPos, nTotalBytes ) );  
 
 }  
 
   
 
 /// <summary>  
 
 /// Sub-thread entry function   
 
 /// </summary>  
 
 /// <param name="stateinfo"></param>  
 
 public void UploadFile( object stateinfo )  
 
 {  
 
 int nRealRead, nBufferSize;  
 
 const int BUFFER_SIZE = 10240;  
 
   
 
 using( FileStream fs = new FileStream( strFileName,  
 
 FileMode.Open, FileAccess.Read,  
 
 FileShare.Read ) )  
 
 {  
 
 string sName = strFileName.Substring( strFileName.LastIndexOf( "http://" ) + 1 );  
 
 byte[] bBuffer = new byte[BUFFER_SIZE];//Init 10k buffer  
 
 fs.Position = nStartPos;  
 
 nRealRead = 0;  
 
 do 
 
 {  
 
 nBufferSize = BUFFER_SIZE;  
 
 if( nRealRead + BUFFER_SIZE > nTotalBytes )  
 
 nBufferSize = nTotalBytes - nRealRead;  
 
   
 
 nBufferSize = fs.Read( bBuffer, 0, nBufferSize );  
 
 if( nBufferSize == BUFFER_SIZE )  
 
 UploadHandle( sName,  
 
 nRealRead + nStartPos,  
 
 bBuffer );  
 
 else if( nBufferSize > 0 )  
 
 {  
 
 //Copy data   
 
 byte[] bytData = new byte[nBufferSize];  
 
 Array.Copy( bBuffer,0, bytData, 0, nBufferSize );  
 
   
 
 UploadHandle( sName,  
 
 nRealRead + nStartPos,  
 
 bytData );  
 
 }  
 
   
 
 nRealRead += nBufferSize;  
 
 }  
 
 while( nRealRead < nTotalBytes );  
 
 }  
 
 //Release signal  
 
 ManualResetEvent mr = stateinfo as ManualResetEvent;  
 
 if( mr != null )  
 
 mr.Set();  
 
 }  
 
 }  
 
   
 
}


發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 崇信县| 西吉县| 东海县| 启东市| 广德县| 古丈县| 黎川县| 霍州市| 河南省| 抚顺市| 朝阳区| 阿拉善右旗| 茌平县| 衡东县| 南昌市| 平乡县| 甘南县| 建湖县| 昭觉县| 玛曲县| 盐城市| 广汉市| 广丰县| 图木舒克市| 阿克陶县| 祁连县| 景宁| 玉环县| 海盐县| 栾川县| 安乡县| 西平县| 扎鲁特旗| 饶河县| 隆安县| 旌德县| 青川县| 两当县| 清水河县| 塘沽区| 青海省|