Home > Software design >  Problem with losing upload path on refresh in ASP.NET Web Forms
Problem with losing upload path on refresh in ASP.NET Web Forms

Time:08-30

I have a problem with losing my files on FileUpload in ASP.NET Web Forms. I am making a website which contains a form where a pdf page and an image should be uploaded by user, and previewed, but when they choose a headline text, font name and font size below uploads, those controls refresh my page and all of the uploaded files are lost. I have tried to add enctype="multipledata" in the form, but it did not work. Does anyone have a clue? Thanks in advance.

<script type="text/javascript">
    function ShowImageBackPreview(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();
            reader.onload = function (e) {
                $('#<%=imagePreview.ClientID%>').prop('src', e.target.result)
                    .width(240)
                    .height(150);
            };
            reader.readAsDataURL(input.files[0]);
        }
    }
</script>

<asp:FileUpload ID="uploadImage" runat="server" CssClass="uploads" onchange="ShowImageBackPreview(this)" />
<asp:Image ID="imagePreview" Height="150px" Width="250px" runat="server" />
<asp:TextBox ID="txtName" runat="server" AutoPostBack="true" placeholder="Name"></asp:TextBox>
<asp:TextBox ID="txtSurname" runat="server" AutoPostBack="true" placeholder="Surname"></asp:TextBox>

When I start to enter the name and the surname, the uploaded shown image is disappeared and also the file path, on each entered text it refreshes the page.

CodePudding user response:

Remove the autopostback for the controls txtName and txtSurName.

A auto post back means the page will post back when you change the values in those controls, and when you post-back, then the file is up-loaded, and your image preview will be lost.

You need a final up-load button on your page that when clicked on will run your code. That upload button can then grab the file up-loaded. You can't have autopostbacks for the text box controls as you show, but then again, there should NOT be ANY requirement for those text box controls to have autopostback=true.

So, remove your autopostback for the controls, and you should be fine.

  • Related