繁体   English   中英

Http请求:编写二进制文本文件(或图像),不包含带有内容配置文件名的标头

[英]Http request: Writing binary text file (or image) without headers with filename from content-disposition

我正在添加文件(字节数组)以通过RestSharp发布数据,并将其发送到node.js Express服务器。 我想用来自content-disposition的文件名写入文件。 我的第一个问题是,使用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' ]

我能想到的唯一解决方案是,使用regex临时写入文件并提取我需要的文件,但我相信这会损坏映像文件,这是由于我没有正确理解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";
        }              
    }
}

这是我相关的node.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
        })
    })
});

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

如果你想进入的文件作为工作流,而不是总是将其保存到磁盘,您可以使用busboy / connect-busboybusboy就是权力multer )来代替。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM