HTTP로 대용량 파일 업로드

· 기능

sgcWebSockets 서버는 서버 메모리에 영향을 주지 않고 대용량 파일을 업로드할 수 있어요. 

HTTP 클라이언트가 multipart/form-data 스트림을 보낼 때 서버는 이 스트림을 메모리에 저장해요. 파일이 크면 서버에서 메모리 부족 예외가 발생할 수 있어요. 이런 예외를 방지하기 위해 서버에는 HTTPUploadFiles라는 속성이 있어요. 이 속성으로 POST 스트림을 어떻게 처리할지(메모리에서 처리할지 파일 스트림으로 처리할지)를 설정할 수 있어요. 스트림이 파일 스트림으로 처리되면 받은 스트림이 바로 하드 디스크에 저장되므로 메모리 문제를 피할 수 있어요.

서버 설정 

서버가 multipart/form-data 스트림을 파일 스트림으로 저장하도록 설정하려면 다음 단계를 따라 주세요:

1. HTTPUploadFiles.StreamType = pstFileStream 속성을 설정해 주세요. 이렇게 설정하면 서버가 이 스트림을 하드 디스크에 저장해요.

2. 파일 스트림으로 저장될 최소 크기(바이트)를 설정할 수 있어요. 기본값은 0이며, 모든 스트림이 파일 스트림으로 저장된다는 의미예요.

3. 스트림이 저장되는 폴더는 SaveDirectory로 지정해요. 설정하지 않으면 애플리케이션과 같은 폴더에 저장돼요.

4. 클라이언트가 multipart/form-data를 보내면 콘텐츠는 boundary 안에 인코딩되어 있어요. RemoveBoundaries 속성이 활성화되어 있으면 전체 스트림을 받은 뒤 boundary 안의 콘텐츠가 자동으로 추출돼요. 

샘플 코드

// 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.