我使用MVC创建了文件上传表单。它可以上传pdf,image,txt等文件,但不能上传Microsoft Word文件。列数据类型为varbinary(Max)。控制器代码:
public ActionResult Create(HttpPostedFileBase postedFile)
{
byte[] bytes;
using (BinaryReader br = new BinaryReader(postedFile.InputStream))
{
bytes = br.ReadBytes(postedFile.ContentLength);
}
string constr = WebConfigurationManager.ConnectionStrings["MyDataModel"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
string query = "INSERT INTO mytable (filedata,mimetype) VALUES (@filepath, @filedata,@mimetype)";
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.Connection = con;
cmd.Parameters.AddWithValue("@filepath", Path.GetFileName(postedFile.FileName));
cmd.Parameters.AddWithValue("@mimetype", postedFile.ContentType);
cmd.Parameters.AddWithValue("@filedata", bytes);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
return View();
}
视图:
@using (Html.BeginForm("Create", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
{
<input type="file" name="postedFile" />
<input type="submit" id="btnUpload" value="Upload" />
}
}
问题出在哪儿?谢谢。
检查Web服务器设置以查看.docx文件是否允许文件类型:
MIME类型:application / vnd.openxmlformats-officedocument.wordprocessingml.document
这取决于Web服务器的类型和版本。
从IIS中的内存中,右键单击网站节点> HTTP标头> Mime类型。