“我想将ID和文件数据发送到同一操作uploadFile(int id,httpPostFileBase upFile)吗?”
我试图在提交过程中通过ajax发送患者ID,并使用输入标签中的name属性来文件。
@using (Html.BeginForm("uploadFile", "patientsProfile", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="upFile" />
<br />
<input type="submit" name="submit" value="Upload!" />
}
var id = url.substring(url.lastIndexOf('/') + 1);
$("form").submit(function (e) {
$.ajax({
type: "POST",
url: "@Url.Action("uploadFile","patientsProfile")",
data: {
Id: id
},
success: function (res) {
alert("id :" + id);
}
})
})
[HttpPost]
public ActionResult uploadFile( HttpPostedFileBase upFile , int Id)
{
Tests tests = new Tests();
tests.patients_Id = Id;
string fileName = upFile.FileName;
string UniquefileName = Guid.NewGuid() + Path.GetFileName(upFile.FileName);
string filePath = Server.MapPath("~/Uploaded/");
string actualPath = Path.Combine(filePath + UniquefileName);
upFile.SaveAs(actualPath);
tests.Name = fileName;
tests.urlName = actualPath;
db.Tests.Add(tests);
db.SaveChanges();
return RedirectToAction("index");
}
httpPostFileBase upFile 为空,但id正确获取其值
答案 0 :(得分:0)
首先,我认为下面的代码会引起问题
var id = url.substring(url.lastIndexOf('/') + 1);
原因
我建议您使用ViewBag
来获取该ID,因为它是通过GET
方法传递的,然后将其作为参数传递给表单,如下所示
@using (Html.BeginForm("uploadFile", "Home", new{Id = ViewBag.Id}, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="upFile" id="upFile" />
<br />
<input type="submit" name="submit" value="Upload!" />
}
请记住将视图包作为
包含在get请求中public ActionResult ActionName(int Id)
{
ViewBag.Id = Id;
return View();
}
如果您坚持使用JavaScript,然后尝试将文件作为数据包含在此answer
中答案 1 :(得分:0)
您必须将upFile
传递到您要发送的数据。
data: {
Id: id,
upFile: //the file which you are sending
},
答案 2 :(得分:0)
@using (Html.BeginForm("uploadFile", "Home", new{Id = ViewBag.Id},
FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="upFile" id="upFile" />
<input type="hidden" name="hdfid" id="hdfid" value ="" />
<br />
<input type="submit" name="submit" value="Upload!" />
}
var id = url.substring(url.lastIndexOf('/') + 1);
$("#hdfid").val(id);
$("form").submit(function (e) {
$.ajax({
type: "POST",
url: "@Url.Action("uploadFile","patientsProfile")",
success: function (res) {
alert("id :" + id);
}
})
})
public ActionResult uploadFile( formcollection form, HttpPostedFileBase
upFile )
{
Tests tests = new Tests();
string id = form["id"];//or provide index
tests.patients_Id = Id;
string fileName = upFile.FileName;
string UniquefileName = Guid.NewGuid() +
Path.GetFileName(upFile.FileName);
string filePath = Server.MapPath("~/Uploaded/");
string actualPath = Path.Combine(filePath + UniquefileName);
upFile.SaveAs(actualPath);
tests.Name = fileName;
tests.urlName = actualPath;
db.Tests.Add(tests);
db.SaveChanges();
return RedirectToAction("index");
}