Http 请求:从内容处置中编写没有标题的二进制文本文件(或图像)

本文关键字:二进制 标题 文本 文件 图像 请求 Http | 更新日期: 2023-09-27 18:37:05

我正在添加一个文件(字节数组)以通过RestSharp发布数据,并将其发送到节点.js快速服务器。我想用内容处置中的文件名写入文件。我的第一个问题是,当使用 fs 将数据写入文件时,它还会写入一个包含一些标头信息的包装器:

-------------------------------28947758029299
Content-Disposition: form-data; name="file"; filename="test.txt"
Content-Type: application/octet-stream
Hello from c#
-------------------------------28947758029299--

另一个问题是,尽管它将其写入文件,但 Content-Disposition 似乎不是标头对象的一部分:

[ 'content-type',
  'accept',
  'x-forwarded-port',
  'user-agent',
  'accept-encoding',
  'content-length',
  'host',
  'x-forwarded-for' ]

我能想到的唯一解决方案是,临时编写文件并使用正则表达式提取我需要的内容,但我相信这会损坏图像文件,除了因为我没有正确理解 http 请求而不是合法解决方案的结果。我对 C# 和 node 都很陌生,所以从我在网上找到的示例中拼凑在一起:

这是我的 C# 代码:

public ActionResult Documents(HttpPostedFileBase file)
{
    if (ModelState.IsValid)
    {
            if (file == null)
            {
                ModelState.AddModelError("File", "Please Upload Your file");
            }
            else if (file.ContentLength > 0)
            {
                var fileName = Path.GetFileName(file.FileName);
                    var inputStream = file.InputStream;
                    System.IO.Stream MyStream;
                    int FileLen = file.ContentLength;
                    byte[] input = new byte[FileLen];
                    // Initialize the stream.
                    MyStream = file.InputStream;
                    // Read the file into the byte array.
                    MyStream.Read(input, 0, FileLen);
                    var client = new RestClient("http://128.199.53.59");
                    var request = new RestRequest(Method.POST);
                    request.AddHeader("Content-Type", "application/octet-stream");
                    request.AddFile("file", input, fileName, "application/octet-stream");
                    RestResponse response = (RestResponse)client.Execute(request);
                    ModelState.Clear();
                    ViewBag.Message = "File uploaded successfully";
        }              
    }
}

这是我的相关节点.js:

app.post('/', function(request, response){
    var fileData = [];
    var size = 0;
    request.on('data', function (chunk) {
        size += chunk.length;
        fileData.push(chunk);
    })
    request.on('end', function(){
        var buffer = Buffer.concat(fileData);
        fs.writeFile('logo.txt', buffer, 'binary', function(err){
            if (err) throw err
        })
    })
});

Http 请求:从内容处置中编写没有标题的二进制文本文件(或图像)

您需要使用 multipart/form-data 解析器。对于快递,有multermultipartyformidable

如果要将传入文件作为流处理,而不是始终将它们保存到磁盘,则可以使用busboy/connect-busboybusboymulter的动力)。