Как проверить размер файла при загрузке фотографии с помощью ajaxupload3.5

Я использую ajaxuploader для загрузки и изменения фотографии пользователя, используя решение здесь: http://www.c-sharpcorner.com/blogs/4183/upload-image-by-ajax-uploader-with-jquery.aspx Код ниже работает нормально, но я не знаю, как проверить размер файла на стороне клиента или (если это невозможно на стороне клиента), как получить ответ со стороны сервера. В mycode под идентификатором ответа указан HTML-код всей страницы.

<script src="../js/jquery-ui-1.8.18.custom.min.js" type="text/javascript"></script>
     <script src="../js/ajaxupload.3.5.js" type="text/javascript"></script>
 <script type="text/javascript" language="javascript">

         $(function () {

             $('#<%=status_message.ClientID%>').html('');
             var btnUpload = $('#upload_button');
             var status = $('#status_message');
             new AjaxUpload(btnUpload, {
                 action: 'test_photoUpload.aspx/uploadPhoto',
                 name: 'uploadfile',
                 onSubmit: function (file, ext) {
                     $('#<%=status_message.ClientID%>').html('');
                     $('#imgLoad').show();
                     if (!(ext && /^(jpg|png|jpeg|gif)$/.test(ext))) {
                         // extension is not allowed
                         $('#imgLoad').hide();
                         $('#<%=status_message.ClientID%>').html('Only JPG, PNG or GIF files are allowed');
                         alert("submitted");
                         return false;
                     }
                     //                     if (file.ContentLength > 1024 * 1024 * 2) {
                     //                         $('#<%=status_message.ClientID%>').html('Please upload photo less than 2MB size.');
                     //                         alert("submitted");
                     //                         return false;
                     //                     }

                 },
                 onComplete: function (file, response) {
                     alert(response);
                     status.text('');
                     $('#<%=hdPhoto.ClientID%>').val(file);
                     $('#<%=imgPhoto.ClientID%>').attr('src', 'UserImages/' + file);
                     // $('#<%=status_message.ClientID%>').html(file.toString());
                     $('#imgLoad').hide();
                     return false;
                 }
             });
         });

        </script>



private string uploadPhoto()
        {
            string chkResult = "false";
            //upload photo code
            string i = Request.Files.ToString();
            string ext = Path.GetExtension(Request.Files[0].FileName.ToString().ToLower());

            if (ext == ".png" || ext == ".jpg" || ext == ".gif" || ext == ".jpeg")
            {
                if (Request.Files[0].ContentLength <= 1024 * 1024 * 2)
                {
                    if (File.Exists(Server.MapPath("UserImages") + "\\" + System.IO.Path.GetFileName(Request.Files[0].FileName)))
                        File.Delete(Server.MapPath("UserImages") + "\\" + System.IO.Path.GetFileName(Request.Files[0].FileName));

                    Request.Files[0].SaveAs(Server.MapPath("UserImages") + "\\" + System.IO.Path.GetFileName(Request.Files[0].FileName));
                    chkResult = "true";
                }
                else
                {
                    status_message.InnerHtml = "Please upload less than 2MB size.";
                    chkResult = "false";
                }
            }
            else
            {
                status_message.InnerHtml = "Please upload only png, jpg, jpeg or gif file.";
                chkResult = "false";
            }
            // Response.Close();
            // Response.End();
            return chkResult;
        }

Я попытался сериализовать ответ Json и вернуть, но ответ - тот же HTML, преобразованный в строку. Я пытался так:

$(function () {

             $('#<%=status_message.ClientID%>').html('');
             var btnUpload = $('#upload_button');
             var status = $('#status_message');
             new AjaxUpload(btnUpload, {
                 action: 'test_photoUpload.aspx/uploadPhoto',
                 name: 'uploadfile',
                 dataType: 'json',
                 contentType: "application/json; charset=utf-8",
                 onSubmit: function (file, ext) {
                     $('#<%=status_message.ClientID%>').html('');
                     $('#imgLoad').show();
                     if (!(ext && /^(jpg|png|jpeg|gif)$/.test(ext))) {
                         // extension is not allowed
                         $('#imgLoad').hide();
                         $('#<%=status_message.ClientID%>').html('Only JPG, PNG or GIF files are allowed');
                         alert("submitted");
                         return false;
                     }
                     //                     if (file.ContentLength > 1024 * 1024 * 2) {
                     //                         $('#<%=status_message.ClientID%>').html('Please upload photo less than 2MB size.');
                     //                         alert("submitted");
                     //                         return false;
                     //                     }

                 },
                 onComplete: function (file, response) {
                     var obj = JSON.stringify(response);
                     //var obj = jQuery.parseJSON(response);
                     alert(obj);
                     alert(response);
                     status.text('');
                     $('#<%=hdPhoto.ClientID%>').val(file);
                     $('#<%=imgPhoto.ClientID%>').attr('src', 'UserImages/' + file);
                     // $('#<%=status_message.ClientID%>').html(file.toString());
                     $('#imgLoad').hide();
                     return false;
                 }
             });
         });

использование System.Web.Script.Serialization; использование System.Web.Script.Services;

 [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        private string uploadPhoto()
        {
            string chkResult = "false";
            //upload photo code
            string i = Request.Files.ToString();
            string ext = Path.GetExtension(Request.Files[0].FileName.ToString().ToLower());

            if (ext == ".png" || ext == ".jpg" || ext == ".gif" || ext == ".jpeg")
            {
                if (Request.Files[0].ContentLength <= 1024 * 1024 * 2)
                {
                    if (File.Exists(Server.MapPath("UserImages") + "\\" + System.IO.Path.GetFileName(Request.Files[0].FileName)))
                        File.Delete(Server.MapPath("UserImages") + "\\" + System.IO.Path.GetFileName(Request.Files[0].FileName));

                    Request.Files[0].SaveAs(Server.MapPath("UserImages") + "\\" + System.IO.Path.GetFileName(Request.Files[0].FileName));
                    chkResult = "true";
                }
                else
                {
                    status_message.InnerHtml = "Please upload less than 2MB size.";
                    chkResult = "false";
                }
            }
            else
            {
                status_message.InnerHtml = "Please upload only png, jpg, jpeg or gif file.";
                chkResult = "false";
            }
            // Response.Close();
            // Response.End();
            //return chkResult;
            var keyValues = new Dictionary<string, string>
               {
                   { "success", "success" },
                   { "error", "error" }
               };

            JavaScriptSerializer js = new JavaScriptSerializer();
            string json = js.Serialize(keyValues);
            //Response.Write(json);
            return json;

        }

Я также пытался использовать метод webmethod и static uploadPhoto, но ответ тот же. Любая помощь приветствуется.

1 ответ

Меня устраивает. Я создаю экземпляр AjaxUpload в переменной, затем использую саму переменную для вызова внешнего скрипта, который отправляет файл. После этого я получаю входную информацию из скрипта AjaxUpload.

var btnUpload = $("#upload");
up_archive = new AjaxUpload(btnUpload, {
    action: 'FileUpload.php',
    name: 'upload_archive',
    responseType: 'json', //get the server response as JSON
    autoSubmit: false, //I'll set some informations about the archive outside this script
    onChange: function(file, ext){
        //check the file size
        if (up_archive._input.files[0].size > 2097152){ //2MB
            //show alert message
            alert('Selected file is bigger than 2MB.');
            return;
        }
    },
    onSubmit: function(file, ext){
        desc_archive = $("#desc_archive").val();

        this.setData( {desc_archive: desc_archive} ); //set a description for the archive to be uploaded
    },
    onComplete: function(file, response){
        $("#desc_archive").val('');
        $("#div_response").html(response.message);
    }
});
Другие вопросы по тегам