我有一个包含多个属性和两个按钮的汽车表格: 第一个按钮是保存汽车属性表单 第二个是上传汽车的照片
问题是照片表有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"
}));
}
答案 0 :(得分:0)
您是否可以在临时文件夹下上传图像并返回表示临时文件夹的GUID?当一切顺利时,将照片移动到您希望他们所在的文件夹,这样,当用户保存汽车时,您总是可以将照片链接到carId。
或者,只有当有效carID大于零时才会启用上传照片按钮(假设您使用了数据库的身份(1,1)或某些guid)