在将对象保存到数据库之前上传对象图像



我有一个汽车窗体,其中包含多个属性和两个按钮: 第一个按钮是保存汽车属性窗体 第二个是上传汽车的照片

问题是照片表具有 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"
}));
}

您能否上传图像而不考虑临时文件夹并返回表示临时文件夹的 GUID? 一切正常后,将照片移动到您希望它们所在的文件夹,这样,当用户保存汽车时,您始终可以将照片链接到您的carId。

或者,仅当有效的carID大于零时,您才能启用上传照片按钮(假设您使用身份(1,1(来自您的数据标签或某些guid(

最新更新