【问题标题】:Why MVC Upload file cannot take word file为什么MVC上传文件不能带word文件
【发布时间】:2018-07-18 13:42:57
【问题描述】:

我使用 MVC 创建了文件上传表单。它可以上传pdf、图片、txt等文件,但不能上传微软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" />
    }

}

问题出在哪里?谢谢。

【问题讨论】:

  • 您使用的是什么类型的服务器? IIS?
  • 上传的错误是什么?
  • 问题出在哪里?你告诉我们。你有错误吗?会发生什么?
  • 请注意,model-view-controller 标签是针对有关模式的问题。 ASP.NET-MVC 实现有一个特定的标记。

标签: asp.net-mvc


【解决方案1】:

检查您的网络服务器设置以查看 .docx 文件是否是允许的文件类型:

MIME 类型: 应用程序/vnd.openxmlformats-officedocument.wordprocessingml.document

这取决于网络服务器的类型和版本。

从 IIS 的内存中,右键单击网站节点 > HTTP Headers > Mime Types。

【讨论】:

  • 我目前正在本地机器上进行测试。错误消息是“System.Data.dll 中发生‘System.Data.SqlClient.SqlException’类型的异常,但未在用户代码中处理其他信息:字符串或二进制数据将被截断。”谢谢。
  • 是docx文件还是替代类型?
  • 感谢您的补充说明
  • 是的,是.docx文件。
  • 啊,我明白了,所以它在 cmd.ExecuteNonQuery(); 处抛出异常;
猜你喜欢
  • 2011-07-09
  • 2011-11-27
  • 1970-01-01
  • 1970-01-01
  • 2011-02-25
  • 2016-06-22
  • 1970-01-01
  • 1970-01-01
  • 2011-09-13
相关资源
最近更新 更多