簡體   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