我想上传并保存文件以及其他具有数据类型int,string和datetime的用户输入数据。我想将文件保存到硬盘驱动器并将路径和其他输入数据保存在SQL Server数据库表中。每当我试图同时做这两件事时,我都会AggregateException
。我是ASP.NET MVC和Web API的新手。
下面是我在ASP.NET MVC项目中的操作方法。
public ActionResult AddOrEdit(mvcCandidate cn)
{
if (cn.ID == 0)
{
if (cn.cvFile.ContentLength != 0)
{
string filename = Path.GetFileNameWithoutExtension(cn.cvFile.FileName);
string extension = Path.GetExtension(cn.cvFile.FileName);
filename = filename + DateTime.Now.ToString("yymmssff") + extension;
cn.path = "~/Uploads/" + filename;
filename = Path.Combine(Server.MapPath("~/Uploads/"), filename);
cn.cvFile.SaveAs(filename);
}
else
cn.path = "";
try
{
HttpResponseMessage response = GlobalVariables.WebApiClient.PostAsJsonAsync("Candidates", cn).Result;
}
catch (AggregateException ex)
{
var ch = ex.Message;
return null;
}
}
}
这是WebAPI项目中的操作方法
public IHttpActionResult PostCandidate(Candidate candidate)
{
db.Candidates.Add(candidate);
db.SaveChanges();
return CreatedAtRoute("DefaultApi", new { id = candidate.ID }, candidate);
}
模型类如下:
public class mvcCandidate
{
public int ID { get; set; }
[Display(Name="Name")]
public string Name { get; set; }
[Display(Name = "Address")]
public string Adress { get; set; }
[Display(Name = "Date Of Birth")]
[DataType(DataType.Date)]
public Nullable<System.DateTime> DOB { get; set; }
public string PIN { get; set; }
public Nullable<int> CompanyID { get; set; }
[Display(Name = "CV")]
public string path { get; set; }
public HttpPostedFileBase cvFile { get; set; }
public virtual mvcCompany Company { get; set; }
}
答案 0 :(得分:0)
在处理Web API时,我一直在努力保存带有数据的文件,所以我设法通过从当前的HttpContext获取属性和文件来解决这个问题,我知道使用绑定要容易得多,不过这样做为我工作,所以保存文件的控制器(API控制器代码)是:
[HttpPost]
public IHttpActionResult SaveFileWithData()
{
try
{
var httpRequest = HttpContext.Current.Request;
#region Get entity data
var entity = new EntityClass();
entity.Name = httpRequest.Params["name"];
//here you put the saving code into entity framework aka Context.Entity.Add(entity); Context.SaveChanges();
#endregion
if (httpRequest.Files.Count > 0)
{
var myFile = httpRequest.Files[0];
var filePath = HttpContext.Current.Server.MapPath($"~/Files/{ myFile.FileName}");
//Set the file into server
myFile.SaveAs(filePath);
}
return Ok();
}
catch (Exception ex)
{
return InternalServerError();
}
}
当从客户端提交数据时,我使用了Multipart表格如下: