Visual Studio没有响应上传大小为6MB的文件

时间:2017-09-29 14:25:11

标签: c# entity-framework-6 httppostedfilebase

我正在使用Visual Studio 15.我的应用程序需要上传大小为6MB的文件。我正在使用带有实体框架6的.Net 4.5.1。

以下脚本和html代码是在视图级别的razor中编写的,用于选择和检查文件的上传。

$('#SaveResponse').click(function () {
var data = new FormData();
var files = $("#imagefile").get(0).files;
    if (files.length > 0) {
        data.append("UploadedImage", files[0]);
    }
    else
    {
        alert('You have not selected any File');
        return;
    }
            $.ajax({
                async: false,
                cache: false,
                type: "POST",
                dataType: "json",
                contentType: false,
                processData: false,
                url: "@(Url.RouteUrl("UploadFile"))",
                data: data,
                success: function (JsonCP) {
                      if (JsonCP.msg != null) {
                        if (JsonCP.msg.Key) {
                            alert(JsonCP.msg.Value);
                            $("#fileUpload").val('');
                        } else 
                            alert(JsonCP.msg.Value);
                      }
                   },
                error: function (JsonCP) {
                    alert(JsonCP.msg.Value);
                 }
            });
        });

<table>
  <tr>
      <td align="right" width="200px">@Html.Label("Select the File:")</td>
      <td  align="left" width="200px"><input type="file" id="imagefile" />
      </td>
  </tr>
  <tr>
   <td colspan="2" align="center"><input type="button" value="Save this 
     Response"  id="SaveResponse" name="SaveResponse" /></td>
  </tr>
</table>

在控制器中编写以下代码以获取要上载的文件并显示相应的消息。

[System.Web.Mvc.AcceptVerbs(HttpVerbs.Post)]
    public ActionResult UploadFile()
    {
        UploadResponseModel rm = new UploadResponseModel();
        try
        {
            if (System.Web.HttpContext.Current.Request.Files.AllKeys.Any())
            {
                var httpPostedFile = 
            System.Web.HttpContext.Current.Request.Files["UploadedImage"];
                if (httpPostedFile != null)
                {
                    string fileSavePath = 
           Path.Combine(HttpContext.Server.MapPath("~/UploadedFiles"), 
              Path.GetFileName(httpPostedFile.FileName));
                    httpPostedFile.SaveAs(fileSavePath);
                    rm.responseModel.response.ResponseImage = 
                       System.IO.File.ReadAllBytes(filesavePath)
                    if (rm.responseModel.insertResponse() != 1)
                        rm.msg = new KeyValuePair<bool, string>(false, 
                            "row is not saved successfully."); 
                    else
                        rm.msg=new KeyValuePair<bool,string>(true,"File 
                          uploaded Successfully.");
                 }
                else
                rm.msg = new KeyValuePair<bool, string>(false, "Could not 
                    get the file.");
            }
            else
          rm.msg = new KeyValuePair<bool, string>(false, "No file found to 
                                 Upload.");
        }
        catch (Exception ex)
        {
     rm.msg = new KeyValuePair<bool, string>(false, "Can not Upload the 
       file: "  + ex.Message);
        }
        return Json(rm, JsonRequestBehavior.AllowGet);
    }
  } 

以下函数用于在sql数据库表中插入一行名为Responses。

public int insertResponse()
{
   using (Entities cntx = new Entities())
   {
    cntx.Responses.Add(this.response);cntx.Entry(this.response).
    State = System.Data.Entity.EntityState.Added;
    int ex=cntx.SaveChanges();
    return ex;
   }
  }

响应表的一列名为responseImage,是fileStream的数据类型。它的另一列是uniqueIdentifier类型。表创建sql如下所示。

CREATE TABLE [dbo].[Responses] (
[ResponseId]       UNIQUEIDENTIFIER           ROWGUIDCOL NOT NULL,
[ResponseImage]    VARBINARY (MAX) FILESTREAM NULL,
     CONSTRAINT [PK_Responses] PRIMARY KEY CLUSTERED ([ResponseId] ASC) 
     FILESTREAM_ON  [FileStreamGroup], UNIQUE NONCLUSTERED ([ResponseId] ASC)
  );

Web confif文件设置如下

<system.web>
  <authentication mode="None" />
  <compilation debug="true" targetFramework="4.5.1" />
  <httpRuntime targetFramework="4.5.1" maxRequestLength="3145728" 
    executionTimeout="9999999" useFullyQualifiedRedirectUrl="false" 
    minFreeThreads="8" minLocalRequestFreeThreads="4" 
    appRequestQueueLimit="1000"/>
</system.web>

<system.webServer>

 <security>
    <requestFiltering>
      <requestLimits maxAllowedContentLength="3221225472" />
   </requestFiltering>
 </security>

程序正常运行并显示小尺寸文件的正确消息,但对于大小为3 MB的文件,它不会显示任何错误消息,甚至内存不足。但行和文件已保存。为什么它上传文件时没有显示任何消息?

2 个答案:

答案 0 :(得分:0)

如果我们直接操作文件流,问题可以通过以下方式解决。

public int insertStreamResponse(HttpPostedFile file)
    {
        SqlConnection sqlConnection = new SqlConnection();
        sqlConnection.ConnectionString = "Data 
        Source=HOME\\MSQLEXPRESS2016;Initial Catalog=Evaluation;Integrated 
         Security=True";
        sqlConnection.Open();
        SqlCommand sqlCommand = new SqlCommand();
        sqlCommand.Connection = sqlConnection;
        sqlCommand.CommandType = CommandType.Text;
        sqlCommand.CommandText = "insert into responses values
        (ResponseId, (0X))";
        SqlParameter parameter;
        parameter = new System.Data.SqlClient.SqlParameter("@ResponseId", 
        System.Data.SqlDbType.UniqueIdentifier);
        parameter.Value = this.response.ResponseId;
        sqlCommand.Parameters.Add(parameter);
        SqlCommand helperCommand = new SqlCommand();
        sqlCommand.Transaction = sqlConnection.BeginTransaction();
        sqlCommand.ExecuteNonQuery();
        helperCommand.Connection = sqlConnection;
        helperCommand.Transaction = sqlCommand.Transaction;
        helperCommand.CommandText = "SELECT 
        GET_FILESTREAM_TRANSACTION_CONTEXT()";
        Object transactionContext = helperCommand.ExecuteScalar();
        helperCommand.CommandText = "SELECT ResponseImage.PathName() FROM 
        Responses WHERE [ResponseId] = @Id";
        parameter = new System.Data.SqlClient.SqlParameter("@Id", 
        System.Data.SqlDbType.UniqueIdentifier);
        helperCommand.Parameters.Add(parameter);
        helperCommand.Parameters["@Id"].Value = sqlCommand.Parameters
        ["@ResponseId"].Value;
        string filePathInServer = (string)helperCommand.ExecuteScalar();
        byte[] buffer = new byte[file.ContentLength];
        //read from the input file 
        Stream fileStream = file.InputStream;
        if (fileStream.CanRead)
            fileStream.Read(buffer, 0, file.ContentLength);
        else return 0;
        //write into the  file stream
        SqlFileStream sqlFileStream = new SqlFileStream(filePathInServer, 
        (byte[])transactionContext, System.IO.FileAccess.Write);
        if (sqlFileStream.CanWrite)
            sqlFileStream.Write(buffer, 0, file.ContentLength);
        else return 0;
        sqlCommand.Transaction.Commit();
        sqlConnection.Close();
        return 1;
    }

答案 1 :(得分:0)

如果您使用IIS托管应用程序,则默认上传文件大小(如果为4MB)。要增加它,请在web.config中使用以下部分 -

<configuration> <system.web> <httpRuntime maxRequestLength="1048576" /> </system.web> </configuration>

对于IIS7及更高版本,您还需要添加以下行:

<system.webServer> <security> <requestFiltering> <requestLimits maxAllowedContentLength="1073741824" /> </requestFiltering> </security> </system.webServer>

注意:maxAllowedContentLength以字节为单位测量,而maxRequestLength以千字节为单位,这就是此配置示例中值不同的原因。 (两者相当于1 GB。)