我只是想让用户上传一个文件。
我有一个简单的开始表单,它包含一个文件元素,如下所示:
@using (Html.BeginForm("LoadData", "Input", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div style="width:23%; display:inline-block;">
<label>Select Type:</label>
<select name="UploadType">
<option value="First">First</option>
<option value="Second">Second</option>
</select>
</div>
<div style="width:43%; display:inline-block;">
<input type="file" name="files1" id="files1" />
</div>
<div style="width:33%; display:inline-block;">
<input type="submit" value="Upload"/>
</div>
}控制人是:
[HttpPost]
public ActionResult LoadData(string UploadType, HttpPostedFileBase file1)
{
if(file1 != null && UploadType != null)
{
Console.WriteLine(file1.FileName);
Console.WriteLine(UploadType);
}
}所有内容都显示并在站点上工作,但是当它回发时文件为null。我看过很多谷歌搜索结果,包括:
Binding HttpPostedFileBase using Ajax.BeginForm
http://www.aurigma.com/upload-suite/developers/aspnet-mvc/how-to-upload-files-in-aspnet-mvc
还有更多。他们都说我的东西是对的。只要名称与文件输入和控制器参数匹配,它就会工作。但事实并非如此。
我试着将它命名为文件、文件,现在命名为file1,但不管我如何称呼它,它都是空的。
我做错了什么?我甚至试过检查Request.Files,但它的计数为0。
发布于 2016-12-07 23:12:25
最后,我使用javascript来处理文件。以下是工作代码:
Javascript (它现在允许多个文件):
function SendData() {
var formData = new FormData(document.querySelector('UploadForm'));
for(var i = 0; i < $('#file')[0].files.length; i++)
{
formData.append('files', $('#file')[0].files[i]);
}
formData.append('samplevalue', $('#samplevalue').val());
var url = $('#baseUrl').val() + 'Input/LoadData';
$.ajax({
url: url,
type: 'POST',
data: formData,
processData: false, // tell jQuery not to process the data
contentType: false, // tell jQuery not to set contentType
success: function (data) {
// your logic....
},
error: function(data)
{
// logic....
}
});
}然后控制器接受
public string LoadData(string samplevalue, HttpPostedFileBase[] files)
{
}当然,诀窍是javascript。我仍然不知道为什么表单不能正常工作,但这是完美的。:)
发布于 2016-05-25 16:58:27
您的文件输入名为files1,但您的操作参数是file1 (没有s)。
发布于 2018-03-13 07:10:54
@using (Html.BeginForm("MethodName", "ControllerName", FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
<input type="file" name="ImgUploader" id="ImgUploader" />
<input type="submit" value="Create" class="btn btn-default" />
}
**Your Controller**`[HttpPost]
public ActionResult Create()
{
HttpPostedFileBase file = Request.Files["ImgUploader"];
}https://stackoverflow.com/questions/37443324
复制相似问题