исключение типа «System.Web.HttpException» при загрузке файла на сервер - PullRequest
0 голосов
/ 28 января 2020

Я новый в asp. net, ajax и c#. Я пытаюсь сохранить изображение на сервере в следующем примере:

        <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
    <title></title>
    </head>
<body>
<form id="form1" runat="server">
        <input type="file" name="postedFile" />
        <input type="button" id="btnUpload" value="Upload" />
        <progress id="fileProgress" style="display: none"></progress>
        <hr />
        <span id="lblMessage" style="color: Green"></span>
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
        <script type="text/javascript">
        $("body").on("click", "#btnUpload", function () {   
$.ajax({
                url: 'Handler.ashx',
                type: 'POST',
                data: new FormData($('form')[0]),
                cache: false,
                contentType: false,
                processData: false,
                success: function (file) {
                    $("#fileProgress").hide();
                    $("#lblMessage").html("<b>" + file.name + "</b> has been uploaded.");
                },
                xhr: function () {
                    var fileXhr = $.ajaxSettings.xhr();
                    if (fileXhr.upload) {
                        $("progress").show();
                        fileXhr.upload.addEventListener("progress", function (e) {
                            if (e.lengthComputable) {
                                $("#fileProgress").attr({
                                    value: e.loaded,
                                    max: e.total
                                });
                            }
                        }, false);
                    }
                    return fileXhr;
                }
            });
        });
        </script>
    </form>
</body>
</html>

Добавлен Generi c Обработчик:

    using System;
using System.IO;
using System.Net;
using System.Web;
using System.Web.Script.Serialization;

namespace RateEatPresentation
{
    /// <summary>
    /// Summary description for Handler
    /// </summary>
    public class Handler : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            //Check if Request is to Upload the File.
            if (context.Request.Files.Count > 0)
            {
                //Fetch the Uploaded File.
                HttpPostedFile postedFile = context.Request.Files[0];

                //Set the Folder Path.
                string folderPath = context.Server.MapPath("~/UsersUploadedImages/");

                //Set the File Name.
                string fileName = Path.GetFileName(postedFile.FileName);

                //Save the File in Folder.
                postedFile.SaveAs(folderPath + fileName);

                //Send File details in a JSON Response.
                string json = new JavaScriptSerializer().Serialize(
                    new
                    {
                        name = fileName
                    });
                context.Response.StatusCode = (int)HttpStatusCode.OK;
                context.Response.ContentType = "text/json";
                context.Response.Write(json);
                context.Response.End();
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

Но я получаю исключение "Исключение типа" System.Web .HttpException 'произошла в System.Web.dll, но не была обработана в коде пользователя ". Я пытался найти что-то подобное, но, к сожалению, не удалось: enter image description here

1 Ответ

1 голос
/ 28 января 2020

Возможно, изображение слишком большого размера, вам нужно просто настроить web.config для их поддержки. По умолчанию IIS поддерживает 4 МБ, вы можете изменить это в Web.config

<system.web>
  <httpRuntime executionTimeout="240" maxRequestLength="20480" />
</system.web>

и

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

. Необходимо изменить maxRequestLength и maxAllowedContentLength

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...