upload file using input control: keep the selected file displayed

 Hello,

I'm using an input control that allows the user to select a file to upload:

<input id="File1" type="file" runat="server" size="60" />

When the user selects a file and after PostBack, the input file control is blank. How do I make it keep the value of the selected file ?

Thanks.

0
ultravi0let
8/14/2008 5:06:51 PM
asp.net.client-side 24353 articles. 2 followers. Follow

19 Replies
1318 Views

Similar Articles

[PageSpeed] 41
Get it on Google Play
Get it on Apple App Store

Hi ultravi0let,

Set EnableViewState property on the FileUpload or INPUT control to "true"

Mausy


If this post answers your question please "mark it as answer" on the title of the post in order to inform other users! Thanks. Mausy
0
mausy
8/14/2008 5:53:01 PM

 Hello mausy,
Tried it. not working.

      <input id="File1" type="file" runat="server" size="60" EnableViewState="true"/>

is there anything else that I need to do to make it work ?

Thanks in advance.

 

Regards,

Sanaa

0
ultravi0let
8/14/2008 6:40:43 PM

There is no way to do that. The filename is cleared by the browser security after the upload.

NC...

 

0
NC01
8/14/2008 6:44:17 PM

 I see ..

Thanks a lot :)

Regards,

Sanaa

0
ultravi0let
8/14/2008 8:14:50 PM

The default behaviour of file input control is that it empty the control's value. Let me suggest some ways you can persist the values or state of the control

- On postback save the values of the control in a textbox

Textbox1.text=File1.PostedFIle.FileName

- Make sure your File Control is inside a form and not inside any UpdatePanel. FileUpload Controls does not work in UpdatePanel Control of Microsoft Ajax Toolkit.

- The second one can be the most obvious reason for not saving the value


Do mark as answer if it helps

Best Regards

Ali Sufyan Butt
Software Engineer
Electronic Solutions Pvt. Limited
0
AliSufyanButt
8/15/2008 4:38:11 AM

 ok, then after saving the value, what do I do with it ?

0
ultravi0let
8/15/2008 7:04:09 PM

The question to ask there is what do you want to do with it?

NC...

 

0
NC01
8/17/2008 2:51:57 PM

Well I wish I could put it back in the input control, but u already answered my question abt that .. I just wanted to follow Ali's point.

Anyway, it's always good to know that it's possible to keep the information..

Regards,

Sanaa

0
ultravi0let
8/17/2008 3:06:04 PM

Well you can't put it back in the upload control, though I can see no reason why you would want to do that since the file would have already been uploaded. Something like this maybe?

<form id="Form1" method="post" runat="server">
 Select a file to upload: <input type="file" id="FileUpload1" runat="Server" name="FileUpload1">
 <input type="submit" id="uploadButton" value="Upload..." onclick="onButtonClick();" runat="Server" OnServerClick="uploadButton_Click">
 File uploaded: <asp:label id="Label1" runat="server"></asp:label>
</form>

<script type="text/JavaScript">
<!--
function onButtonClick()
{
 alert(document.getElementById("FileUpload1").value);
 window.status = 'Uploading file: ' + document.getElementById("FileUpload1").value;
}
// -->
</script>

protected void uploadButton_Click(object sender, EventArgs e)
{
 // FileUpload1.Value == FileUpload1.PostedFile.FileName

 if ( FileUpload1.PostedFile != null )
 {
  try
  {
   Label1.Text = FileUpload1.PostedFile.FileName;
   string uploadFilePath = "complete-path-to-upload-file-to";
   FileUpload1.PostedFile.SaveAs(uploadFilePath);
   this.Response.Write("Successful upload!<br>");
  }
  catch(Exception ex)
  {
   this.Response.Write("Error saving file: " + FileUpload1.Value + "<br>" + ex.ToString() + "<br>");
  }
 }
}

NC...

0
NC01
8/18/2008 12:00:00 PM

You can fetch the value later on from the textbox and use in your codebehind file, as per the logic is required in your application. NC's example is good but i think not very conclusive enough. as i do not see the usage of the value anywhere.


Do mark as answer if it helps

Best Regards

Ali Sufyan Butt
Software Engineer
Electronic Solutions Pvt. Limited
0
AliSufyanButt
8/21/2008 6:11:23 AM

AliSufyanButt:

You can fetch the value later on from the textbox and use in your codebehind file, as per the logic is required in your application. NC's example is good but i think not very conclusive enough. as i do not see the usage of the value anywhere.

Mostly because I can see no usage for the value (which is what I posted if you would read my post). Also, the OP seems reluctant to tell us what he wants to use it for.

NC...

 

0
NC01
8/21/2008 11:53:26 AM

Your are right NC01, most of the guys are reluctant in defining their exact requirements. While they should. Obviously we would help them in a better way if the requirements are crystal clear. I am being active for around a month, and very few questions i replied to seems like reasonable to answer. Most of them time we need to cross examine multiple time what the question really is. Sometimes after four five posts the person clears his exact thoughts. :)


Do mark as answer if it helps

Best Regards

Ali Sufyan Butt
Software Engineer
Electronic Solutions Pvt. Limited
0
AliSufyanButt
8/28/2008 11:10:14 AM

AliSufyanButt:

Your are right NC01, most of the guys are reluctant in defining their exact requirements. While they should. Obviously we would help them in a better way if the requirements are crystal clear. I am being active for around a month, and very few questions i replied to seems like reasonable to answer. Most of them time we need to cross examine multiple time what the question really is. Sometimes after four five posts the person clears his exact thoughts. :)

And it seems to be getting worse in the last few months. More complete newbies? I don't know.

NC...

 

0
NC01
8/28/2008 11:42:19 AM

NC01:

AliSufyanButt:

Your are right NC01, most of the guys are reluctant in defining their exact requirements. While they should. Obviously we would help them in a better way if the requirements are crystal clear. I am being active for around a month, and very few questions i replied to seems like reasonable to answer. Most of them time we need to cross examine multiple time what the question really is. Sometimes after four five posts the person clears his exact thoughts. :)

And it seems to be getting worse in the last few months. More complete newbies? I don't know.

NC...

What do you mean by more complete newbies.. pointing toward me Big Smile I am working in IT industry for 4.2 years. Joined this great site few months ago.


Do mark as answer if it helps

Best Regards

Ali Sufyan Butt
Software Engineer
Electronic Solutions Pvt. Limited
0
AliSufyanButt
8/28/2008 11:45:51 AM

No, not you Smile. More like posters who don't even want to learn .NET and expect us to write their complete application for them. For example.

I want to create a web application that selects a file, validates it, uploads it, and turns it into an image.

NC...

 

0
NC01
8/28/2008 11:50:20 AM

You are right NC01, 100% right. What can we do, open forum. Free for everyone.


Do mark as answer if it helps

Best Regards

Ali Sufyan Butt
Software Engineer
Electronic Solutions Pvt. Limited
0
AliSufyanButt
8/28/2008 11:57:31 AM
Hello, 

Been on a vacation, so haven't been able to answer back your last comments.

There's no one reluctant here. I thought I asked my question very clearly, I just needed to put the value back to the input control, but I understood it was not possible as NC01 kindly explained.

The only reason why I did not go through long explanations of what I'm doing is because I don't want to bug anyone with the details and write a very long, so I choosed to ask my question in a direct and concise way. But since you seem a little disappointed here’s the story:

I have a form with input controls and “Upload” button. I allow the user to add input controls dynamically with an “Add a new image” button, so he can upload as many images as he wants.

<script type="text/javascript">

function addFileUploadBox()

{

    if (!document.getElementById || !document.createElement)

        return false;

           

    var uploadArea = document.getElementById ("upload-area");

     

    if (!uploadArea)

        return;

 

    var newLine = document.createElement ("br");

    uploadArea.appendChild (newLine);

     

      ////ajout du text

      var newUploadText = document.createElement ("<input type='text' size='1' readonly='readonly' disabled='disabled'  />");

    if (!newUploadText.lastAssignedId)

        newUploadText.lastAssignedId = 100;

    if (!addFileUploadBox.lastAssignedId)

        addFileUploadBox.lastAssignedId = 100;

 

    newUploadText.value = parseInt(addFileUploadBox.lastAssignedId) - 98;

 

    newUploadText.setAttribute ("id", "dynamic" + addFileUploadBox.lastAssignedId);

    newUploadText.setAttribute ("name", "dynamic:" + addFileUploadBox.lastAssignedId);

   

      ////ajout de l'input

    var newUploadBox = document.createElement ("input");

    newUploadBox.type = "file";

    newUploadBox.size = "60";

    if (!addFileUploadBox.lastAssignedId)

        addFileUploadBox.lastAssignedId = 100;

    newUploadBox.setAttribute ("id", "dynamic" + addFileUploadBox.lastAssignedId);

    newUploadBox.setAttribute ("name", "dynamic:" + addFileUploadBox.lastAssignedId);

   

    uploadArea.appendChild (newUploadText);

    uploadArea.appendChild (newUploadBox);

   

    addFileUploadBox.lastAssignedId++;

}

function AddFile_onclick() {

 

}

    </script>

 

<i style="font-family: Verdana; font-size: 9pt;">Images jpg uniquement.</i>

        <p id="upload-area">

            <input id="inputText1" type="text" runat="server" size="1" readonly="readonly" disabled="disabled"

                value="1" /><input id="File1" type="file" runat="server" size="60" enableviewstate="true" />

        </p>

        <input id="AddFile" type="button" value="Ajouter une autre image" onclick="addFileUploadBox()"

            onclick="return AddFile_onclick()" style="font-family: verdana" /><br />

        <br />

        <div align="center">

            <asp:Button ID="btnSubmit" runat="server" Text="Upload" OnClick="btnSubmit_Click"

                Width="242px" Font-Names="Verdana" ValidationGroup="Val1" />

 

    protected void btnSubmit_Click(object sender, EventArgs e)

    {

        try

        {

            HttpFileCollection uploads = HttpContext.Current.Request.Files;

 

            //chemin de l'application PageTurn

            DAApplication da = new DAApplication();

            string AppPath = da.getApplicationPath();

 

            DALivre dalivre = new DALivre();

            string FolderName = dalivre.getFolderNameByIDLivre(Convert.ToInt32(ddlLivre.SelectedItem.Value));

 

            for (int i = 0; i < uploads.Count; i++)

            {

                HttpPostedFile upload = uploads[i];

 

                if (upload.ContentLength == 0) // if no image in the current input, next

                    continue;

 

                string FileName = System.IO.Path.GetFileName(upload.FileName); // We don't need the path, just the name.

 

                string FileExtention = System.IO.Path.GetExtension(upload.FileName);

 

                if (FileExtention != ".jpg")

                {

                    lblMessage.Text = "jpg only !";

                    return;

                }

 

                upload.SaveAs(@AppPath + "\\img\\" + FolderName + "\\page" + i.ToString() + ".jpg");

                lblMessage.Text = "Upload terminé.";

                lblMessage.Text += "<br />Emplacement des images : \"" + AppPath + "\\img\\" + FolderName + "\"";

 

            }

        }

        catch (Exception Exp)

        {

            lblMessage.Text = "Echec lors de l'upload : <br />" + Exp.ToString();

        }

    }

 

The selected images are uploaded to the specified path. Now only JPG images are allowed. The thing is, if the user chooses an image which is not jpg, he gets the « jpg only !" » message, no upload is performed and the input control gets back empty. I wanted to make the user able to see what he has selected after getting the error message. This is why I needed to put the value back to the input. And I wanted to use the « tip » for other forms where I have many static input controls, so the user can correct the wrong selections only without having to select all the files over again. I got the answer to my question and left my form as is, so I guess I’m done here.

Hope my 2 miles post satisfies everyone !

Regards,

Sanaa RAMZI

0
ultravi0let
9/9/2008 12:14:35 PM

Just change your message as follows:

if ( FileExtention != ".jpg" )
{
 lblMessage.Text = "Cannot upload " + FileName + " We allow jpg only !";

 return;
}

NC...

0
NC01
9/9/2008 12:49:56 PM

Well that was quite a general comment. Not pin pointing at you. Smile


Do mark as answer if it helps

Best Regards

Ali Sufyan Butt
Software Engineer
Electronic Solutions Pvt. Limited
0
AliSufyanButt
9/10/2008 7:16:05 AM
Reply: