你能告诉我为什么没有上传文件,我只得到文件名吗?
我没有收到任何错误消息,所有信息都可以在DB中加载好吗?
我正在使用LINQ to SQL MVC4
表格ID - CompanyNameCon - PdfCon
控制器:
[HttpPost]
public ActionResult Create(DAT_SupplyCon DAT_SupplyCon, HttpPostedFileBase file)
{
if (ModelState.IsValid)
{
DAT_SupplyCon.PdfCon = FileUpload.UploadFile(file);
db.DAT_SupplyCons.InsertOnSubmit(DAT_SupplyCon);
db.SubmitChanges();
return RedirectToAction("Index");
}
return View(DAT_SupplyCon);
}
视图
@model CFire2.Models.DAT_SupplyCon
@{
ViewBag.Title = "Create";
}
<h2>Create</h2>
<script src="~/Scripts/jquery-1.8.2.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
@using (Html.BeginForm("Create", "DAT_SupplyCons", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.ValidationSummary(true)
<fieldset>
<legend>DAT_SupplyCon</legend>
<div class="editor-label">
@Html.LabelFor(model => model.SupplierCon)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.SupplierCon)
@Html.ValidationMessageFor(model => model.SupplierCon)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.CompanyNameCon)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.CompanyNameCon)
@Html.ValidationMessageFor(model => model.CompanyNameCon)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.PdfCon)
</div>
<div class="editor-field">
<input type="file" name="file" />
@Html.ValidationMessageFor(model => model.PdfCon)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
的Utils:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
namespace CFire2.Utils
{
public static class FileUpload
{
public static char DirSeparator =
System.IO.Path.DirectorySeparatorChar;
public static string FilesPath = "Content" +
DirSeparator + "Uploads" + DirSeparator;
public static string UploadFile(HttpPostedFileBase file)
{
if (null == file) return "";
if (!(file.ContentLength > 0)) return "";
string fileName = file.FileName;
string fileExt = Path.GetExtension(file.FileName);
if (null == fileExt) return "";
if (!Directory.Exists(FilesPath))
{
Directory.CreateDirectory(FilesPath);
}
string path = FilesPath + DirSeparator + fileName;
file.SaveAs(Path.GetFullPath(path));
return fileName;
}
public static void DeleteFile(string fileName)
{
if (fileName.Length == 0) return;
string path = FilesPath + DirSeparator + fileName;
if (File.Exists(Path.GetFullPath(path)))
{
File.Delete(Path.GetFullPath(path));
}
}
}
}
答案 0 :(得分:0)
也许Server.MapPath
是解决方案。例如:
var path = Path.Combine(HttpContext.Current.Server.MapPath("~/Content"), fileName);
file.SaveAs(path);