2017-09-29 53 views
2

我正在使用Visual Studio 15.我的應用程序需要上傳大小爲6MB的文件。我正在使用.Net 4.5.1與實體框架6.Visual Studio沒有響應上傳6MB大小的文件

下面的腳本和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> 

下面的代碼被寫入控制器到達要上傳的文件並顯示相應的消息。

[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

Visual Studio 15:您的意思是VS2015(v14.x)還是VS2017(v15.x)? –

+0

我看到你有客戶端,服務器端和SQL Server邏輯。您是否能夠調試以檢查三個組件中的前兩個或後兩個之間的問題? –

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

這是爲了回答問題,還是對問題的修正? –

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)