如何将文件保存到磁盘?

Posted

技术标签:

【中文标题】如何将文件保存到磁盘?【英文标题】:How do I save a file to disk? 【发布时间】:2011-02-25 00:09:25 【问题描述】:

这是我的控制器:

    [HttpPost]
    public ActionResult Index(HttpPostedFileBase excelFile)
    

        /*Somewhere here, I have to save the uploaded file.*/

        var fileName = string.Format("0\\1", Directory.GetCurrentDirectory(), excelFile.FileName);
        var connectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0; data source=0; Extended Properties=Excel 8.0;", fileName);

        var adapter = new OleDbDataAdapter("SELECT * FROM [workSheetNameHere$]", connectionString);
        var ds = new DataSet();
        adapter.Fill(ds, "results");

        DataTable data = ds.Tables["results"];

        return View();
    

【问题讨论】:

你到底想保存什么到磁盘? excelFile 是上传到网站的文件。 .xlsx 文件。我需要将该文件永久保存到硬盘驱动器。我猜使用 .InputStream 属性?但我对如何做到这一点感到困惑。 如果您只是想知道如何保存 excelFile,我们不需要与数据库对话的其余代码 - 这很令人困惑。只需提供最少量的代码。 【参考方案1】:

如果您正在接收上传的文件,这是一种处理方式。

string nameAndLocation = "~/UploadedFiles/" + hpf.FileName;
hpf.SaveAs(Server.MapPath(nameAndLocation));

【讨论】:

我想他是在问关于专门保存 excelFile 的问题。 谢谢,这有点帮助。 :)【参考方案2】:

你试过HttpPostedFileBase.SaveAs方法吗?

【讨论】:

我没有看到那个方法。 :) 只是一个问题,如果我只给它一个要使用的文件名,它会将文件保存在哪里? 如果只指定文件名,则将当前目录作为文件的位置。您可能更喜欢不使用 Directory.GetCurrentDirectory,而是使用 Server.MapPath 将您网站中的某些相对路径映射到物理路径。例如,Server.MapPath(@"~/ExcelFiles/data.xls")【参考方案3】:
[HttpPost]
public ActionResult Index(HttpPostedFileBase excelFile)

   /*Somewhere here, I have to save the uploaded file.*/

   var fileName = string.Format("0\\1", Directory.GetCurrentDirectory(), excelFile.FileName);

   excelFile.SaveAs(fileName );

   //...

如有疑问,请查看文档: http://msdn.microsoft.com/en-us/library/system.web.httppostedfilebase.saveas.aspx

【讨论】:

以上是关于如何将文件保存到磁盘?的主要内容,如果未能解决你的问题,请参考以下文章

如何将 Excel 工作簿保存到磁盘?

Alamofire 没有将文件保存到磁盘

如何将 MailMessage 对象作为 *.eml 或 *.msg 文件保存到磁盘

如何将 base64 编码的图像保存到磁盘?

PHP 将 zip 保存到磁盘

如何压缩整个文件夹(带有子文件夹)并通过 Flask 提供它而不将任何内容保存到磁盘