我有MVC application
它有浏览按钮我正在选择文件任何位置并使用路径读取文件内容,然后处理内容。
在本地工作正常,但是当作为Web应用程序发布在Azure上时,显然无法获取文件系统路径,但是如何处理?
找不到文件"D:\Windows\system32\mydata.json"。
Index.cshtml
<label>File Path</label>
<table>
<tr>
<td>@Html.TextBoxFor(m => m.filePath, new { type = "file", @class = "input-file" }) )</td>
<td> </td>
</tr>
</table>
首页控制器.cs
private static void Test(string filepath)
{
string data = System.IO.File.ReadAllText(filepath);
JArray array = JArray.Parse(data);
在 Azure 上,进程当前工作目录为D:Windowssystem32
,尝试var wholePath = Path.Combine(Server.MapPath("~/"), filepath);
在 Web 根目录下查找文件。
更新
HttpPostedFileBase
字段添加到模型中。在您的视图中,更改为m => m.File
。
public class FileModel
{
public HttpPostedFileBase File { get; set; }
}
在控制器中
public ActionResult FileUpload(FileModel fileModel)
{
if (ModelState.IsValid)
{
StreamReader s = new StreamReader(fileModel.File.InputStream);
JArray array = JArray.Parse(s.ReadToEnd());
...
}
return View();
}
您正在尝试读取客户端计算机上在服务器上执行的代码中的文件。那行不通。您的服务器无权访问客户端计算机中的文件。这是一件好事 😁
看看 HttpPostedFileBase 上传文件。