簡體   English   中英

如何解析 HTTP POST(文件上傳)流?

[英]how to parse HTTP POST(file upload) stream?

我正在使用 actionscript 引擎上傳文件,引擎將選擇文件並通過 HTTP POST 命令通過網絡發送文件,文檔說 POST 消息如下:

POST /handler.cfm HTTP/1.1
  Accept: text/*
  Content-Type: multipart/form-data; 
  boundary=----------Ij5ae0ae0KM7GI3KM7ei4cH2ei4gL6 
  User-Agent: Shockwave Flash 
  Host: www.example.com 
  Content-Length: 421 
  Connection: Keep-Alive 
  Cache-Control: no-cache

  ------------Ij5GI3GI3ei4GI3ei4KM7GI3KM7KM7
  Content-Disposition: form-data; name="Filename"

  MyFile.jpg
  ------------Ij5GI3GI3ei4GI3ei4KM7GI3KM7KM7
  Content-Disposition: form-data; name="photo"; filename="MyFile.jpg"
  Content-Type: application/octet-stream

  FileDataHere
  ------------Ij5GI3GI3ei4GI3ei4KM7GI3KM7KM7
  Content-Disposition: form-data; name="Upload"

  Submit Query

  ------------Ij5GI3GI3ei4GI3ei4KM7GI3KM7KM7--

在服務器端,我有一個 C++ 程序偵聽端口 80 並解析 POST 消息。 我只想要文件名和文件數據。 如何使用 C++ 解碼文件數據,它是否是 base64 編碼的,是否有庫可以為我完成? 我想解碼二進制文件,並將其寫入文件,謝謝!

不,沒有編碼。 多部分消息的每個子部分的正文作為逐字字節包括在內。 因此,您必須小心選擇不會出現在文件數據中的任何地方的boundary字符串。

要解析 multipart/form-data 表單提交,您將需要足夠的 MIME 解析器來解析標頭,挑選出您想要的參數,例如boundaryname ,並通過邊界字符串拆分接收到的消息。 這並非完全微不足道,因此您可能需要考慮現有庫

(不幸的是,瀏覽器在 HTTP 中實際執行的操作與RFC 1341 中概述的標准 MIME 規則略有不同。特別是,字段名和文件名參數往往包含非 ASCII 字符和未轉義的引號。但如果您希望自己生成 POST您可以避開這些有爭議的領域。)

在沒有“Content_Transfer_Encoding”標頭的情況下,假定數據以“7bit”編碼( RFC 1521RFC 1867RFC 2616 )。

我不知道是否有一個C庫來解析/解碼 HTTP POST。 我很確定有:)

您可以上傳無限大小的data/file 試試這個解決方案

const char* ctype = "multipart/form-data; boundary=----WebKitFormBoundaryfm9qwXVLSbFKKR88";
size_t content_length = 1459606;
http_payload* hp = new http_payload(ctype, content_length);
if (hp->is_multipart()) {
    int ret = hp->read_all("C:\\temp\\");
    if (ret < 0) {
        std::cout << hp->get_last_error() << std::endl;
        hp->clear();
    }
    else {
        std::string dir_str("C:\\upload_dir\\");
        ret = hp->read_files([&dir_str](http_posted_file* file) {
            std::string path(dir_str.c_str());
            path.append(file->get_file_name());
            file->save_as(path.c_str());
            file->clear(); path.clear();
            std::string().swap(path);
        });
        hp->clear();
        std::cout << "Total file uploaded :" << ret << std::endl;
    }
}
else {
    int ret = hp->read_all();
    if (ret < 0) {
        std::cout << hp->get_last_error() << std::endl;
        hp->clear();
    }
    else {
        std::cout << "Posted data :" << hp->get_body() << std::endl;
        hp->clear();

    }
}

https://github.com/safeonlineworld/web_jsx/blob/0d08773c95f4ae8a9799dbd29e0a4cd84413d108/src/web_jsx/core/http_payload.cpp#L402

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM