HTTP POST 大文件上传

· 功能

sgcWebSockets 服务器支持发布大文件,且不会影响服务器内存。

当 HTTP 客户端发送 multipart/form-data 流时,该流会被服务器保存在内存中。当文件较大时,服务器可能会引发内存不足异常。为避免此类异常,服务器提供了名为 HTTPUploadFiles 的属性,您可以配置 POST 流的处理方式:保存在内存中或作为文件流处理。若选择文件流方式,接收到的流将直接存储在硬盘上,从而避免内存问题。

Server Configuration 

要配置服务器将 multipart/form-data 流保存为文件流,请按以下步骤操作:

1. 设置属性 HTTPUploadFiles.StreamType = pstFileStream。使用此设置,服务器将把这些流存储在硬盘上。

2. 您可以配置文件以文件流方式存储的最小字节数。默认值为零,即所有流都将以文件流方式存储。

3. 使用 SaveDirectory 指定流的存储目录;若未设置,将存储在应用程序所在目录。

4. 当客户端发送 multipart/form-data 时,内容被编码在边界(boundary)中;若启用 RemoveBoundaries 属性,则在接收到完整流后,边界内的内容将被自动提取。

示例代码

// First create a new server instance and set the Streams are saved as File Streams.
oServer := TsgcWebSocketHTTPServer.Create(nil);
oServer.Port := 5555;
oServer.HTTPUploadFiles.StreamType := pstFileStream;
oServer.Active := True;
// Then create a new html file with the following configuration
<html>
    <head><title>sgcWebSockets - Upload Big File</title></head>
    <body>
        <form action="http://127.0.0.1:5555/file" method="post" enctype="multipart/form-data">
            <input type="file" name="file_1" />
            <input type="submit" />
        </form>
    </body>
</html>
// Finally open the html file with a web browser and send a file to the server. 
// The server will create a new file stream with the extension ".sgc_ps" and when the stream is fully received, 
// it will extract the file from the boundaries.