[Step by step] [update] resumable upload on Windows Mobile

Source: Internet
Author: User
Tags microsoft iis

Cause: the company has Project Resumable upload is used. Development But because of Environment (The principle is to use aspnet_isapi. DLL To respond to put and post requests ). Mode To those who have helped me (pkwsh, egmkang, etc)
1. Principle of resumable data transfer (from Network )
Learn more HTTP Before proceeding to the principle of resumable data transfer, let's talk about the HTTP protocol. HTTP is a simple TCP-based protocol, divided into two types: request and reply.
The request protocol is composed ( Browser The protocol used to send a message when a request is submitted to the server (Web Server. The reply protocol is composed
Server. Both request and response protocols are composed of headers and bodies. The header and body are separated by a blank line.
The following is a request message and the corresponding reply message Example :
GET/image/index_r4_c1.jpg http/ 1.1
Accept :*/*
Referer: http: // 192.168.3.120: 8080/
Accept-language: ZH-CN
Accept-encoding: gzip, deflate
User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0;. Net CLR 1.0.3705)
HOST: 192.168.3.120: 8080
Connection: keep-alive
HTTP/1.1 200 OK
Server: Microsoft-Microsoft IIS/5.0
Date: Tue, 24 Jun 2003 05:39:40 GMT
Content-Type: image/JPEG
Accept-ranges: bytes
Last-modified: Thu, 23 May 2002 03:05:40 GMT
Etag: "bec48eb862c21: 934"
Content-Length: 2827
....

Next we will talk about "resumable upload ".
As the name implies, resumable upload is the last timeDownloadStart to download. You can add rang to the request header in the HTTP protocol.
Segment e to indicate where the client wants to continue downloading.
For example, when downloading from 1,024th bytes, the request message is as follows:

GET/image/index_r4_c1.jpg http/ 1.1
Accept :*/*
Referer: http: // 192.168.3.120: 8080/
Accept-language: ZH-CN
Accept-encoding: gzip, deflate
User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0;. Net CLR 1.0.3705)
HOST: 192.168.3.120: 8080
Value Range: bytes = 1024-
Connection: keep-alive

Related Classes in. net
After understanding the above principles, let's take a look at the classes provided by. NET Framework for us to do these things.

Complete HTTP Request
System. net. httpwebrequest

HttpwebrequestDefinitionProvides support for attributes and methodsUserCan directly interact with servers using HTTP
To provide support for additional attributes and methods.

Httpwebrequest will be sent to the InternetResourcesThe public HTTP header value of is public as an attribute by the method orSystemSet. The following table is complete.List
. You can set other headers in the headers attribute to name/value pairs. However, note that some public headers are considered restricted.
ByAPIPublic, or protected by the system, cannot be changed. Range is also protected. However,. NET provides more convenient operations for developers.
The addrange method is used to add a slave request to the request.DataByte range header at the beginning or end

CompleteFileAccess
System. Io. filestream

FilestreamObjectYou can use the seek method to randomly access files. Seek allows you to move the read/write location to any location in the file. This
It is done through the parameter of the byte offset reference point. The Byte offset is relative to the query reference point. The reference point can be the start of the basic file.
The front position or the end are represented by three attributes of the seekorigin class.

2. examples that can be run online
CodeImplementation
After learning about the classes provided by. net, we can easily implement them.

The Code is as follows:

Static void main (string [] ARGs)
{
String strfilename = "C: \ aa.zip"; // set it based on the actual situation
String strurl = "http://www.xxxx.cn/xxxxx.zip"; // set as needed

// Open the last downloaded file or create a new file
Long lstartpos = 0;
System. Io. filestream FS;
If (system. Io. file. exists (strfilename ))
{
FS = system. Io. file. openwrite (strfilename );
Lstartpos = FS. length;
FS. Seek (lstartpos, system. Io. seekorigin. Current); // you can specify
Needle
}
Else
{
FS = new system. Io. filestream (strfilename, system. Io. filemode. Create );
Lstartpos = 0;
}
// Open the network connection
Try
{
System. net. httpwebrequest request = (system. net. httpwebrequest) system. net
. Httpwebrequest. Create (strurl );
If (lstartpos> 0)
Request. addrange (INT) lstartpos); // sets the range value.
// Request from the server to obtain the Server Response Data Stream
System. Io. Stream NS = request. getresponse (). getresponsestream ();
Byte [] nbytes = new byte [512];
Int nreadsize = 0;
Nreadsize = NS. Read (nbytes, 0,512 );
While (nreadsize> 0)
{
FS. Write (nbytes, 0, nreadsize );
Nreadsize = NS. Read (nbytes, 0,512 );
}
FS. Close ();
NS. Close ();
Console. writeline ("download completed ");
}
Catch (exception ex)
{
FS. Close ();
Console. writeline ("error occurred during download:" + ex. tostring ());
}
3. Server Configuration

Configure a site and read andRunPermission
4. Improved (with simple logic, multipleThread)

  1. # Region Author: wt0731, 2010-01-02
  2. /*
  3. * Release: 1.0
  4. * Maintainer:
  5. * Latest maintenance Date:
  6. *
  7. */
  8. # Endregion
  9. Using system;
  10. Using system. Collections. Generic;
  11. Using system. componentmodel;
  12. Using system. Data;
  13. Using system. drawing;
  14. Using system. text;
  15. Using system. Windows. forms;
  16. Using system. Threading;
  17. Namespace downloadfile
  18. {
  19. Public partial class formdownload: Form
  20. {
  21. Private thread threaddownload = NULL;
  22. Private thread threadupload = NULL;
  23. /// <Summary>
  24. /// Download path
  25. /// </Summary>
  26. Private string downloadpath = "http: // 192.168.100.46/httphandle/2.rar"; // modify it as needed
  27. /// <Summary>
  28. /// Local storage path
  29. /// </Summary>
  30. Private string localsourcefile = string. empty;
  31. /// <Summary>
  32. /// Pause
  33. /// </Summary>
  34. Private bool dlthreadcontinue = false;
  35. Public formdownload ()
  36. {
  37. Initializecomponent ();
  38. This. btnstop. Enabled = false;
  39. }
  40. Private void btndownload_click (Object sender, eventargs E)
  41. {
  42. Cursor. Current = cursors. waitcursor;
  43. This. btndownload. Enabled = false;
  44. This. dlthreadcontinue = true;
  45. This. btnstop. Enabled = true;
  46. Localsourcefile = system. environment. getfolderpath (environment. specialfolder. Personal) + "\" + this.txt name. Text. tostring (); // set it based on actual conditions
  47. Downloadpath = this.txt URL. Text. tostring (); // set according to the actual situation
  48. Threaddownload = new thread (New threadstart (downloadthread ));
  49. Threaddownload. Start ();
  50. }
  51. /// <Summary>
  52. /// Download thread entryFunction
  53. /// </Summary>
  54. Void downloadthread ()
  55. {
  56. Downloadfile (this. downloadpath, this. localsourcefile );
  57. }
  58. /// <Summary>
  59. /// Download the file without compression
  60. /// </Summary>
  61. /// <Param name = "serverurl"> address used by the server to process HTTP requests </param>
  62. /// <Param name = "FILENAME"> name of the local file </param>
  63. Private void downloadfile (string serverurl, string filename)
  64. {
  65. // Open the last downloaded file or create a new file
  66. Long lstartpos = 0;
  67. System. Io. filestream FS;
  68. If (system. Io. file. exists (filename ))
  69. {
  70. FS = system. Io. file. openwrite (filename );
  71. Lstartpos = FS. length;
  72. FS. Seek (lstartpos, system. Io. seekorigin. Current); // Move the current pointer in the file stream
  73. }
  74. Else
  75. {
  76. FS = new system. Io. filestream (filename, system. Io. filemode. Create );
  77. Lstartpos = 0;
  78. }
  79. // Open the network connection
  80. Try
  81. {
  82. System. net. httpwebrequest request = (system. net. httpwebrequest) system. net. httpwebrequest. Create (serverurl );
  83. Request. keepalive = true;
  84. If (lstartpos> 0)
  85. Request. addrange (INT) lstartpos); // sets the range value.
  86. System. Text. Encoding utf8 = system. Text. encoding. default;
  87. // Request from the server to obtain the Server Response Data Stream
  88. System. Io. Stream NS = request. getresponse (). getresponsestream ();
  89. Byte [] nbytes = new byte [1024];
  90. Int nreadsize = 0;
  91. Nreadsize = NS. Read (nbytes, 0, 1024 );
  92. While (nreadsize> 0 & dlthreadcontinue)
  93. {
  94. FS. Write (nbytes, 0, nreadsize );
  95. Nreadsize = NS. Read (nbytes, 0, 1024 );
  96. }
  97. // Fs. Flush ();
  98. FS. Close ();
  99. NS. Close ();
  100. Cursor. Current = cursors. default;
  101. MessageBox. Show ("download completed", "SystemPrompt");
  102. }
  103. Catch (exception ex)
  104. {
  105. Cursor. Current = cursors. default;
  106. FS. Close ();
  107. MessageBox. Show ("error occurred during download:" + ex. tostring (), "system prompt ");
  108. }
  109. }
  110. Private void menuitem1_click (Object sender, eventargs E)
  111. {
  112. Application. Exit ();
  113. }
  114. Private void btnstop_click (Object sender, eventargs E)
  115. {
  116. If (this. btnstop. Text = "Suspend ")
  117. {
  118. This. dlthreadcontinue = false;
  119. Cursor. Current = cursors. default;
  120. This. btndownload. Enabled = true;
  121. This. btnstop. Enabled = false;
  122. }
  123. }
  124. }
  125. }

Copy code

Extended materials:
Httpwebrequest & httpwebresponse Headers
Introduction
This section briefly describes how to use httpwebrequest and httpwebresponse to directly interact with the HTTP server. the httpwebrequest class supports attributes and methods defined in webrequest. Do not use the constructor of the httpwebrequest object to initiate a request to the HTTP server. Instead, use webrequest. create () method to initialize the new httpwebrequest object. if the Uniform Resource Identifier scheme is "http: //" or "https: //", create () returns the httpwebresponse object.
Code
First, we need to create a new httpwebrequest object. The Code is as follows:
Httpwebrequest myrequest = (httpwebrequest) webrequest. Create (New uri ("urlstring "));
Note: As mentioned above, do not use the httpwebrequest constructor to create objects. Use the webrequest. Create () method to convert the type of an httpwebrequest object.
Next, you can perform simple operations on the newly initialized object. For example, you can set its header attribute,
The following table lists the headers set by properties or methods or by the system:
________________________________________

Header setting method
Accept is set by the accept attribute
Connection is set by the connection attribute and keepalive attribute.
Content-Length is set by the contentlength attribute.
Content-Type is set by the contenttype attribute
CT is set by CT attributes
Date is set by the system to the current date
Host is set by the system to the current host information
If-modified-since is set by the ifmodifiedsince attribute
Range is set by the range attribute.
Transfer-encoding is set by the transferencoding attribute
Referer is set by the Referer attribute
The User-Agent is set by the useragent attribute.
________________________________________
Note: httpwebrequestAutomatic Before using a URL starting with "http: //" or "https: //", you do not need to call the registerprefix Method for registration.
Source code Download: Test the source code downloadfile.rar. (354.25 KB)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.