Почему входной файл кэширует старые загруженные изображения? - PullRequest
0 голосов
/ 20 сентября 2019

У меня есть всплывающее окно bootstrap modal, которое позволяет пользователю выбирать изображения для загрузки, поэтому, когда пользователь выбирает изображения, у меня есть функция javascript, которая добавляет новое <div>, содержащее имя файла, затем пользователь нажимает кнопку Сохранить, чтобы сохранитьизображения в базе данных, все работает, за исключением того, что входной файл кэширует старые изображения и загружает их снова с вновь выбранными изображениями.

<asp:UpdatePanel runat="server" UpdateMode="Conditional" ID="functionalUpdatePanel">
                <ContentTemplate>
    <button title="إضافة مرفق" data-toggle="modal" class="uploadAttach" data-target="#myModal" ></button>

    <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria- 
                labelledby="myModalLabel" aria-hidden="true">
            <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria- 
                hidden="true"> </button>
                <h4 class="modal-title" id="myModalLabel">إضافة مرفق</h4>
                </div>
                <div class="modal-body">
                <asp:Label ID="lblMessage" runat="server" ForeColor="Green" />                  

                    <h5 style="margin-right:45%;font-weight:bold;font- 
                      size:1.2em">اختر المرفق</h5>             

                    <div class="uploadBtnDiv">


                        <input 
             style="cursor:pointer;opacity:0;width:100%;height:100%"  
                    title="اختيار مرفق" type="file" id="myFile" name="myFile"   
                   multiple="multiple" />

                    </div>      

                    <br />
                    <br />

                </div>
                <div class="modal-footer">

                 <asp:UpdatePanel runat="server" UpdateMode="Conditional">
                                                <ContentTemplate>
                                                    <asp:Button style="width:100% 
                    !important;" Text="حفظ" title="إرسال المرفق" CssClass="btn 
                    btn-success" runat="server" ID="btnUpload" 
                     OnClick="btnUploadClick"      />
                                                 </ContentTemplate>
                                                <Triggers>
                                                    <asp:PostBackTrigger 
                     ControlID="btnUpload" />
                                                </Triggers>
                                            </asp:UpdatePanel>
                </div>
            </div> 
            </div> 
        </div> 
             </ContentTemplate>
                <Triggers>


                </Triggers>
            </asp:UpdatePanel>

и вот моя функция java-скрипта

  $(document).on('change', '#myFile:visible', function() {

    var files = $(this)[0].files;
    var newLine;

    for (var i = 0; i < files.length; i++) {

        newLine = "<div class='attach-line'>" +
                    "<div class='attach-name'>" +

            files[i].name.slice(0,25)+'...' +

            "<i    class='icon-trash remove attach-delete'></i>" +

                    "</div>" +
                      "<br/>"+   
                  "</div>";

        $("#myModal .modal-body").append(newLine);

        // Clone the file selector, assign the name, hide and append it
        $(this).clone().hide().attr('name', 'myFile[]').insertAfter($(this));

      }
      $(".remove").click(function(){
            $(this).parent(".attach-name").remove();
          });
});

и ниже указан код

 protected void btnUploadClick(object sender, EventArgs e)
        {

            DataTable dt = new DataTable();
            dt.Columns.Add("AppId", typeof(int));
            dt.Columns.Add("Bytes", typeof(byte[]));
            dt.Columns.Add("ImgNames", typeof(string));
            dt.Columns.Add("ImgType", typeof(string));
            dt.Columns.Add("DedicatedMemberId", typeof(int));


            for (int i = 0; i < Request.Files.Count; i++)
            {
                if (Request.Files[i] != null && Request.Files[i].ContentLength > 0)
                {

                    string fType = Request.Files[i].ContentType.Split('/')[1];
                    string fName = Path.GetFileName(Request.Files[i].FileName);
                    byte[] bytes = new BinaryReader(Request.Files[i].InputStream).ReadBytes(Request.Files[i].ContentLength);
                    dt.Rows.Add(Convert.ToInt32(hfAppId.Value), bytes, fName,
                        fType, Convert.ToInt32(ViewState["memberId"]));
                }
            }
            string outputStr = AppsOperations.UpdateAttach("إرفاق صورة جديدة", "الطلبات ", dt, User.Identity.Name);

            if (outputStr == "s")
            {

                string redirectStr = "AuditApp.aspx?seq=" + hfAttSeq.Value + "&&AppType=" + hfAppType.Value + "&&id=" + hfAppId.Value;
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('تم تحميل المرفق بنجاح');window.location='" + redirectStr + "';", true);

            }
            else if (outputStr == "f")

            {

                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('" + "تعذر تحميل المرفق" + "')", true);

            }

        }

1 Ответ

0 голосов
/ 20 сентября 2019

Я могу найти ответ, на самом деле я использую тот же код на другой странице для кэширования изображений для использования, поэтому я удалил эту нижнюю строку из функции java-скрипта

$(this).clone().hide().attr('name', 'myFile[]').insertAfter($(this));
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...