简体   繁体   English

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

[英]Visual studio is not responding to upload a file of size 6MB

I am working on Visual studio 15. My application needs to upload a file of size 6MB. 我正在使用Visual Studio15。我的应用程序需要上传一个大小为6MB的文件。 I am using .Net 4.5.1 with Entity Framework 6. 我在实体框架6中使用.Net 4.5.1。

The following script and html code is written at view level razor to select and check uploading of file. 以下脚本和html代码是在视图级别的剃刀上编写的,用于选择和检查文件的上传。

$('#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>

The following code is written in the controller to get the file to be uploaded and display appropriate message. 将以下代码写入控制器,以获取要上传的文件并显示相应的消息。

[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);
    }
  } 

The following function is used to insert a row in sql database table called Responses. 以下函数用于在称为响应的sql数据库表中插入一行。

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;
   }
  }

One of the column of responses table called responseImage is datatype of fileStream. 响应表的一列称为responseImage是fileStream的数据类型。 Another column of it is of type uniqueIdentifier. 它的另一列是uniqueIdentifier类型。 The table creation sql is given below. 表创建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)
  );

The Web confif file is set like this 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>

The program works correctly and shows proper message for files of small size, But for the files of size 3 MB it does not show any error message not even out of memory. 该程序可以正常工作,并且会为小文件显示正确的消息,但是对于3 MB的文件,它甚至不会显示出内存不足也不会显示任何错误消息。 But the row and file are saved. 但是该行和文件已保存。 Why it is not showing any message although it is uploading the file? 尽管它正在上传文件,但为什么不显示任何消息?

if we are manipulating the file stream directly the problem can be solved in thr following way. 如果我们直接操作文件流,则可以通过以下方式解决该问题。

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;
    }

If you are using IIS for hosting your application, then the default upload file size if 4MB. 如果您使用IIS托管应用程序,则默认的上载文件大小为4MB。 To increase it, please use this below section in your web.config - 要增加它,请在web.config中使用以下部分-

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

For IIS7 and above, you also need to add the lines below: 对于IIS7及更高版本,您还需要添加以下几行:

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

Note: maxAllowedContentLength is measured in bytes while maxRequestLength is measured in kilobytes, which is why the values differ in this config example. 注意:maxAllowedContentLength以字节为单位,而maxRequestLength以千字节为单位,这就是在此配置示例中值不同的原因。 (Both are equivalent to 1 GB.) (两者均相当于1 GB。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM