我想在編輯模式下編輯其他東西,但我不想重新上傳編輯模式下的圖像文件,該模式已經在create模式。所以我想在編輯模式下查看圖像的路徑。如何在ASP.Net中更新上傳的文件並刪除舊的文件MVC
public ActionResult Edit(HttpPostedFileBase file, FileUpload fileupload)
{
if (ModelState.IsValid)
{
if (file != null)
{
string fil = System.IO.Path.GetFileName(file.FileName);
string path = System.IO.Path.Combine(Server.MapPath("~/Content/Uploads/Files/"), fil);
file.SaveAs(path);
fileupload.FileURL = "/Content/Uploads/Files/" + file.FileName;
}
db.Entry(fileupload).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(fileupload);
}
和編輯視圖模式是:
@using (Html.BeginForm("Edit", "FileUploadTest", FormMethod.Post, new { enctype = "multipart/Form-data" }))
{
@Html.AntiForgeryToken()
<label for="file">Upload Image:</label>
<input type="file" name="file" id="file" style="width:50%" />
<input type="submit" value="Save" class="btn btn-default" />
}
我已經上傳了使用創建操作/查看方法的文件。
我該如何做到這一點?
我使用'Image'作爲一個單獨的對象來討論'Model'。例如,一篇新聞文章可能有一張圖片。當我編輯(或添加)時,我檢查圖像是否已上傳,並**將圖像追加爲數據庫中的相關對象。在這種情況下,也許你可以在圖像頁面有一個'hidden'字段,並將你的'file'輸入重命名爲與提交時檢查相關的非模型。這樣,如果沒有圖像上傳,隱藏字段將被使用,現有的文件路徑仍然存在。 – scgough
什麼是你的'FileUpload'模型?這是什麼你想改變沒有重載圖像? –
@teovankot我使用簡單的模型來保存圖像的路徑。 public class FileUpload { public int FileUploadId {get;組; } public string FileURL {get;組; } } – userKG