我正在尝试使用ASP上传一个JSON文件。但是,由于某些奇怪的原因,我所使用的控件只转发文件名,而不转发路径。
这是我在我的.cshtml里做的事情
<form asp-page-handler="AddDevices" method="post" >
<button
class="btn btn-default"
id="btn_add_devices"
>
Add Devices
</button>
<input type="file" name="fileNameAndPath" accept="application/JSON"/>
</form>...and,下面是在相应的.cs中调用的函数
public void OnPostAddDevices(string fileNameAndPath)
{
string jsonString = System.IO.File.ReadAllText(fileNameAndPath);
[Deserialization]
}问题是,与我想要到达该函数的文件名和路径不同,只传递文件名,因此,例如,如果我使用文件选择器来选择文件C:/TestFiles/TestJson.json,那么在函数OnPostAddDevices中,参数fileNameAndPath的值仅为TestJson.json,而不是我需要的C:/TestFiles/TestJson.json。
当然,这随后导致了一个FileNotFoundException。
在这种情况下,如何使输入传递带有路径的完整文件名?
发布于 2021-12-18 14:48:32
下面是我现在所做的事情,以及基于下面的教程我感到满意的工作:
https://learn.microsoft.com/en-us/aspnet/core/mvc/models/file-uploads?view=aspnetcore-6.0
概括起来:
在我的index.cshtml中,我为“上传”按钮添加了以下内容:
<form enctype="multipart/form-data" method="post">
<dl>
<dt>
<label asp-for="FormFile"></label>
</dt>
<dd>
<input asp-for="FormFile" type="file">
</dd>
</dl>
<input asp-page-handler="UploadDeviceFile" class="btn" type="submit" value="Upload">
</form>在我的Index.cshtml.cs中,我为上传逻辑添加了以下内容:
[BindProperty]
public IFormFile FormFile { get; set; }
public async Task<IActionResult> OnPostUploadDeviceFileAsync()
{
using (var memoryStream = new MemoryStream())
{
await FormFile.CopyToAsync(memoryStream);
string jsonString = Encoding.ASCII.GetString(memoryStream.ToArray());
DeviceContainer deviceContainer = JsonConvert.DeserializeObject<DeviceContainer>(jsonString);
DatabaseController.AddAll(deviceContainer.Devices);
}
return Page();
}https://stackoverflow.com/questions/70392058
复制相似问题