如何从InputStremed文件获取更多信息?

问题描述:

如果我使用的是InputStream接收文件,像如何从InputStremed文件获取更多信息?

HttpContext.Current.Request.InputStream 

如何获取有关文件的更多信息?

我可以很容易地将一个流转换成一个物理文件,但例如,我怎么会知道文件扩展名使用

string fileIn = @"C:\Temp\inputStreamedFile.xxx"; // What extension? 

using (FileStream fs = System.IO.File.Create(fileIn)) 
{ 
    Stream f = HttpContext.Current.Request.InputStream; 
    byte[] bytes = new byte[f.Length]; 
    f.Read(bytes, 0, (int)f.Length); 
    fs.Write(bytes, 0, bytes.Length); 
} 

这背后的想法是因为使用HttpPostedFileBase我总是得到空:

public ContentResult Send(HttpPostedFileBase fileToUpload, string email) 
{ 
    // Get file stream and save it 

    // Get File in stream 
    string fileIn = Path.Combine(uploadsPath, uniqueIdentifier), 
      fileOut = Path.Combine(convertedPath, uniqueIdentifier + ".pdf"); 

    // Verify that the user selected a file 
    if (fileToUpload != null && fileToUpload.ContentLength > 0) 
    { 
     // extract only the fielname 
     string fileExtension = Path.GetExtension(fileToUpload.FileName); 
     fileIn = String.Concat(fileIn, fileExtension); 

     fileToUpload.SaveAs(fileIn); 
    } 

    // TODO: Add Convert File to Batch 

    return Content("File queued for process with id: " + uniqueIdentifier); 
} 

,这就是我的命令行发送:

$ curl --form email='[email protected]' --form fileToUpload='C:\temp\MyWord.docx' http://localhost:64705/send/ 
File queued for process with id: 1d777cc7-7c08-460c-8412-ddab72408123 

变量email填写正确,但fileToUpload始终为空。

P.S. 如果我使用表单上传相同的数据,则不会发生

上传文件,我发现用卷曲......我忘记@迹象提的是,上传的形式将被编码为multipart/form-data唯一的问题。

正确的curl命令使用HttpPostedFileBase是:

$ curl --form email='[email protected]' 
     --form [email protected]'C:\temp\MyWord.docx' 
     http://localhost:64705/send/ 

对不起,如果这没有帮助,但为什么使用InputStream获取上传的文件?

这是我平时做:

[HttpPost] 
public ActionResult Upload(HttpPostedFileBase[] files) { 
    String physicalPath = "c:\\whatever"; 
    foreach (var file in files) { 
     String extension = Path.GetExtension(file.FileName); 
     file.SaveAs(physicalPath + "\\" + file.FileName); 
    } 
    return View(); 
} 
+0

+1,正是.. –

+0

因为我想用卷曲,PowerShell和其他脚本语言使用此,我不想一个文件上传页。一个例子是作为一个calDav解析器,所有的电子邮件客户端发送'.ics'文件作为输入流,虽然我使用的库可以直接从Stream中读取,但现在我试图使一个简单的PDF转换器在命令行中使用。 – balexandre

+1

@balexandre,只要你的客户端支持'multipart/form-data'(尊重客户端,比如cURL),你可以毫无问题地使用'HttpPostedFileBase'。 –

你可以得到有关从<input type="file" />发布文件中的信息。但实际上它的使用有点不同的方式在asp.net mvc的check out here

+0

我知道如何在MVC中上传文件,我只想使用InputStream。 – balexandre