【发布时间】:2018-01-29 04:54:09
【问题描述】:
我有一个汽车表单,其中包括几个属性和两个按钮: 第一个按钮是保存汽车属性表单 第二个是上传汽车的照片
问题是照片表有 carId 属性 当这辆车没有被保存时,carId 将为空 如果用户在保存汽车属性之前尝试上传汽车,则会出现错误 如果他保存了汽车门廊,他会被重定向到主页,并且不会上传照片
上传图片的代码
public ActionResult SaveUploadedFile(int carId)
{
int id = Convert.ToInt32(carId);
bool isSavedSuccessfully = true;
string fName = "";
try
{
foreach (string fileName in Request.Files)
{
HttpPostedFileBase file = Request.Files[fileName];
//Save file content goes here
if (file != null)
{
fName = file.FileName;
if (file.ContentLength > 0)
{
var originalDirectory = new DirectoryInfo($"{Server.MapPath(@"\")}Images");
var pathString = Path.Combine(originalDirectory.ToString(), "carimages");
var isExists = Directory.Exists(pathString);
if (!isExists)
Directory.CreateDirectory(pathString);
var path = $"{pathString}\\{fName}";
file.SaveAs(path);
var image = new PhotoUpload()
{
Name = Path.GetFileNameWithoutExtension(fName),
Extension = Path.GetExtension(fName),
CarId = id
};
_context.PhotoUploads.Add(image);
_context.SaveChanges();
}
}
}
}
catch (Exception)
{
isSavedSuccessfully = false;
}
if (isSavedSuccessfully)
{
return Json(new { Message = fName });
}
else
{
return Json(new { Message = "Error in saving file" });
}
}
保存汽车的代码
public ActionResult Save(CarDto carDto)
{
var client = new HttpClient { BaseAddress = new
Uri("http://localhost:54490") };
switch (carDto.Id)
{
case 0:
var id = User.Identity.GetUserId();
carDto.CarOwnerId = id;
client.PostAsJsonAsync<CarDto>("Api/cars", carDto)
.ContinueWith((postTask) =>
postTask.Result.EnsureSuccessStatusCode());
break;
default:
client.PutAsJsonAsync<CarDto>("Api/cars", carDto)
.ContinueWith((postTask) =>
postTask.Result.EnsureSuccessStatusCode());
break;
}
return new RedirectResult(Url.Action("Index", "Manage", new
{
id = 1,
tab = "myCars"
}));
}
【问题讨论】:
标签: asp.net-mvc forms file-upload