Multipart download and resumable upload are implemented by the response header content-range. Before sending a download response, check whether the request header contains a range header. If yes, set the response status code (statuscode) to 206, at the same time, the number of bytes to be sent for this response is calculated based on the length value in the range request header, and the response is sent in a fixed format in the Content-range Response Header mode.
Private sub dodownload () sub dodownload (byval abspath as string) 'use absolute path parameters
Dim filename as string = dlutil. cutfilename (abspath) 'cutfilename is used to limit the Object Name Length
Dim urlencfilename as string = httputility. urlencode (filename, system. Text. encoding. utf8)
'Send download streams
Dim FS as filestream
Dim buffer (dlbufsize) as byte 'read/write operation Buffer
Dim actualbuflen as integer = 1' actual number of bytes read into the buffer zone
Dim POS as int64, Len as int64
Try
'Check the file existence
If not file. exists (abspath) then
Throw new ioexception ("the file requested to be downloaded does not exist or is unavailable! ") 'In fact, this exception information is not displayed
End if
'Additional Response Headers
Response. Clear ()
Response. clearheaders ()
Response. contenttype = "application/octet-stream"
Response. appendheader ("content-disposition", "attachment; filename =" & urlencfilename &"")
'Open source file
FS = new filestream (abspath, filemode. Open, fileaccess. Read, fileshare. Read)
Len = FS. Length
'Send the response header of the file length. If the request is a resume request, the content-range response header is sent again.
If request. headers ("range") <> string. Empty then
Response. statuscode = 206.
Pos = request. headers ("range"). Replace ("bytes =", ""). Replace ("-","")
End if
Response. appendheader ("Content-Length", len-Pos)
If POS> 0 then
'Response format: Content-range: bytes [start byte of the file block]-[total file size-1]/[total file size]
Response. appendheader ("content-range", "bytes" & Pos & "-" & (LEN-Pos) & "/" & Len)
End if
'Push data
FS. Position = pos' read files starting from the position of this request
While actualbuflen> 0
If response. isclientconnected then
Actualbuflen = FS. Read (buffer, 0, dlbufsize)
Response. outputstream. Write (buffer, 0, actualbuflen)
Response. Flush ()
Redim buffer (dlbufsize)
Else
Actualbuflen = 0
End if
End while
Catch ex as exception
Throw ex
Finally
If not (FS is nothing) then
FS. Close ()
End if
Response. End () 'the global transfer ends and the response object is closed.
End try
End sub