ITW*_*ker 3 html c# asp.net-mvc razor
我有以下剃刀代码:
<div class="container">
@Html.ValidationSummary(false)
@using (Html.BeginForm("EncryptFile", "Encryption", new { returnUrl = Request.Url.AbsoluteUri }, FormMethod.Post, new { @id = "encryptionform", @class = "form-horizontal" }))
{
<div class="form-group">
@Html.Label("File", new { @class = "control-label col-md-2" })
<div class="col-md-10">
<input type="file" id="encryptfilefield" name="uploadedfile" enctype='multipart/form-data'/>
</div>
</div>
<button type="submit" id="encryptfilebutton">Encrypt</button>
<button id="decryptfilebutton" type="button">Decrypt</button>
<button id="reencryptfilebutton" type="button">Re-Encrypt</button>
}
</div>
Run Code Online (Sandbox Code Playgroud)
当我单击“加密”按钮时,将调用以下控制器代码:
[HttpPost]
public ActionResult EncryptFile(string uploadedfile)
{
/*process the file without uploading*/
return Json(new { status = "success", message = "Encrypted!" });
}
Run Code Online (Sandbox Code Playgroud)
当我单击加密按钮时,我可以执行此操作,但uploadedfile字符串始终以null. 如何获取所选文件的填充文件路径?请注意,我并没有尝试将其上传到服务器(尽管名称中出现了“已上传”),我只需要文件路径。
编辑
我在 IE 11 中看到以下内容完全显示了文件路径(警报内的部分):
alert($("#encryptfilefield").val());
然而,这不是一个完整的解决方案,由于它是一个安全问题,似乎没有解决方案。谢谢你。
更新答案
不幸的是,没有办法在所有浏览器中一致地获取这些信息。这里有很多关于这个主题的帖子,结论是浏览器出于安全目的不允许这样做。
我确实发现在 IE 11 中,它们确实在输入 dom 元素 .value 属性中包含了路径,但我不知道这是否适用于其他版本,并且它不适用于 chrome。
$('input[type=file]').change(function () {
console.dir(this.value);
console.dir(this.files[0])
})
Run Code Online (Sandbox Code Playgroud)
不幸的是,这是您所能期望的最好的结果。这是一篇文章,其中包含一些您可以做的事情来实现一些非常具体的场景。
如何使用javascript,jquery-ajax在<input type='file'>更改时获取所选文件的完整路径?
原始答案(如何获取文件路径“之后”到达服务器)
我在想的空参数问题是因为 MVC 绑定了元素名称属性。
<input type="file" id="encryptfilefield" name="uploadedfile" enctype='multipart/form-data'/>
Run Code Online (Sandbox Code Playgroud)
并且您的控制器操作被标记为类型字符串,这不是您的输入类型。
你可以把它改成这个,
[HttpPost]
public ActionResult EncryptFile(HttpPostedFileBase uploadedfile)
{
Run Code Online (Sandbox Code Playgroud)
或者尝试直接从 Request 对象中获取文件,如下所示,您必须在获得它的完整路径之前将其保存在某处,但我不相信您会获得它起源的文件路径,只有在之后你保存它。
[HttpPost]
public ActionResult EncryptFile(string uploadedfile)
{
HttpPostedFileBase myfile = Request.Files[0];
if (file.ContentLength > 0)
{
// extract only the fielname
var fileName = Path.GetFileName(file.FileName);
// store the file inside ~/App_Data/uploads folder
var path = Path.Combine(Server.MapPath("~/App_Data/uploads"),fileName);
file.SaveAs(path);
}
/*process the file without uploading*/
return Json(new { status = "success", message = "Encrypted!" });
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
24451 次 |
| 最近记录: |