Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. Web Development
  3. ASP.NET
  4. Help with fileupload object

Help with fileupload object

Scheduled Pinned Locked Moved ASP.NET
helpcsssysadminquestion
15 Posts 2 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • T Offline
    T Offline
    turbosupramk3
    wrote on last edited by
    #1

    I have the following on my page

    <asp:FileUpload ID="flupldDisplayPicture" runat="server" onClick="flupldDisplayPicture_Click"/>

    but it will not call the function flupldDisplayPicture_Click? If I change the opening tag to protected void flupldDisplayPicture_Click(object sender, EventArgs e) { FileUpload FileUploadControl = new FileUpload(); if (FileUploadControl.HasFile) { try { if (FileUploadControl.PostedFile.ContentType == "image/jpeg") { if (FileUploadControl.PostedFile.ContentLength < 102400) { string filename = Path.GetFileName(FileUploadControl.FileName); FileUploadControl.SaveAs(Server.MapPath("~/") + filename); //StatusLabel.Text = "Upload status: File uploaded!"; //imgDisplayPicture.ImageUrl = ("~/") + filename; imgDisplayPicture.ImageUrl = filename; } else { //StatusLabel.Text = "Upload status: The file has to be less than 100 kb!"; } } else { //StatusLabel.Text = "Upload status: Only JPEG files are accepted!"; } } catch (Exception ex) { //StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message; } } }

    Richard DeemingR 1 Reply Last reply
    0
    • T turbosupramk3

      I have the following on my page

      <asp:FileUpload ID="flupldDisplayPicture" runat="server" onClick="flupldDisplayPicture_Click"/>

      but it will not call the function flupldDisplayPicture_Click? If I change the opening tag to protected void flupldDisplayPicture_Click(object sender, EventArgs e) { FileUpload FileUploadControl = new FileUpload(); if (FileUploadControl.HasFile) { try { if (FileUploadControl.PostedFile.ContentType == "image/jpeg") { if (FileUploadControl.PostedFile.ContentLength < 102400) { string filename = Path.GetFileName(FileUploadControl.FileName); FileUploadControl.SaveAs(Server.MapPath("~/") + filename); //StatusLabel.Text = "Upload status: File uploaded!"; //imgDisplayPicture.ImageUrl = ("~/") + filename; imgDisplayPicture.ImageUrl = filename; } else { //StatusLabel.Text = "Upload status: The file has to be less than 100 kb!"; } } else { //StatusLabel.Text = "Upload status: Only JPEG files are accepted!"; } } catch (Exception ex) { //StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message; } } }

      Richard DeemingR Offline
      Richard DeemingR Offline
      Richard Deeming
      wrote on last edited by
      #2

      The FileUpload control[^] doesn't have a server-side "click" event. You'll either need to handle the click event for the button that causes the form to submit, or use the Page_Load event and check the IsPostBack property. Uploading Files in ASP.NET 2.0[^] Uploading Files (C#) | The ASP.NET Site[^] You'll probably want to add some checks to make sure the file name ends with an expected extension. It would be quite possible for a hacker to submit a request with a valid "web.config" file, but spoof the content type as "image/jpeg". You should probably also save the uploaded files in a specific directory, which should be configured as "no-execute" in IIS.


      "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

      "These people looked deep within my soul and assigned me a number based on the order in which I joined" - Homer

      T 1 Reply Last reply
      0
      • Richard DeemingR Richard Deeming

        The FileUpload control[^] doesn't have a server-side "click" event. You'll either need to handle the click event for the button that causes the form to submit, or use the Page_Load event and check the IsPostBack property. Uploading Files in ASP.NET 2.0[^] Uploading Files (C#) | The ASP.NET Site[^] You'll probably want to add some checks to make sure the file name ends with an expected extension. It would be quite possible for a hacker to submit a request with a valid "web.config" file, but spoof the content type as "image/jpeg". You should probably also save the uploaded files in a specific directory, which should be configured as "no-execute" in IIS.


        "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

        T Offline
        T Offline
        turbosupramk3
        wrote on last edited by
        #3

        Thanks for the reply. I have something similar to that and for discussion and testings sake I am now using the code from the first link. My question is, when I choose a file in the fileupload box, how can I trigger an event? Do I use event handlers like with c# or can I use a worker thread in the background to monitor if fileUpload1.HasFile is true or not?

        C#

        <%@ Page Language="C#" %>

        <script runat="server">
        protected void Button1_Click(object sender, EventArgs e)
        {
        if (FileUpload1.HasFile)
        try
        {
        FileUpload1.SaveAs("C:\\Uploads\\" +
        FileUpload1.FileName);
        Label1.Text = "File name: " +
        FileUpload1.PostedFile.FileName + "<br>" +
        FileUpload1.PostedFile.ContentLength + " kb<br>" +
        "Content type: " +
        FileUpload1.PostedFile.ContentType;
        }
        catch (Exception ex)
        {
        Label1.Text = "ERROR: " + ex.Message.ToString();
        }
        else
        {
        Label1.Text = "You have not specified a file.";
        }
        }
        </script>

        <html xmlns="http://www.w3.org/1999/xhtml" >
        <head runat="server">
        <title>Upload Files</title>
        </head>
        <body>
        <form id="form1" runat="server">
        <div>
        <asp:FileUpload ID="FileUpload1" runat="server" /><br />
        <br />
        <asp:Button ID="Button1" runat="server" OnClick="Button1_Click"
        Text="Upload File" /> <br />
        <br />
        <asp:Label ID="Label1" runat="server"></asp:Label></div>
        </form>
        </body>
        </html>

        Richard DeemingR 1 Reply Last reply
        0
        • T turbosupramk3

          Thanks for the reply. I have something similar to that and for discussion and testings sake I am now using the code from the first link. My question is, when I choose a file in the fileupload box, how can I trigger an event? Do I use event handlers like with c# or can I use a worker thread in the background to monitor if fileUpload1.HasFile is true or not?

          C#

          <%@ Page Language="C#" %>

          <script runat="server">
          protected void Button1_Click(object sender, EventArgs e)
          {
          if (FileUpload1.HasFile)
          try
          {
          FileUpload1.SaveAs("C:\\Uploads\\" +
          FileUpload1.FileName);
          Label1.Text = "File name: " +
          FileUpload1.PostedFile.FileName + "<br>" +
          FileUpload1.PostedFile.ContentLength + " kb<br>" +
          "Content type: " +
          FileUpload1.PostedFile.ContentType;
          }
          catch (Exception ex)
          {
          Label1.Text = "ERROR: " + ex.Message.ToString();
          }
          else
          {
          Label1.Text = "You have not specified a file.";
          }
          }
          </script>

          <html xmlns="http://www.w3.org/1999/xhtml" >
          <head runat="server">
          <title>Upload Files</title>
          </head>
          <body>
          <form id="form1" runat="server">
          <div>
          <asp:FileUpload ID="FileUpload1" runat="server" /><br />
          <br />
          <asp:Button ID="Button1" runat="server" OnClick="Button1_Click"
          Text="Upload File" /> <br />
          <br />
          <asp:Label ID="Label1" runat="server"></asp:Label></div>
          </form>
          </body>
          </html>

          Richard DeemingR Offline
          Richard DeemingR Offline
          Richard Deeming
          wrote on last edited by
          #4

          You'd have to use client-side code to initiate a post-back. For example:

          <asp:FileUpload runat="server" onchange="this.form.submit()" />

          protected void Page_Load(object sender, EventArgs e)
          {
          if (IsPostBack)
          {
          ProcessFileUpload();
          }
          }

          Background threads almost never make sense in ASP.NET, due to the way it works:

          1. The browser makes a request to the server;
          2. The server maps the request to a handler - in this case, you page;
          3. The server creates an instance of your page to handle the request;
          4. The page builds its control tree;
          5. If the request is a "post-back", the page rehydrates the control tree from the saved state sent in the request;
          6. The page runs through the event handlers, and renders an HTML document;
          7. The document is sent back to the client, and the page instance is destroyed;
          8. The client parses and displays the HTML document - this can involve making further requests, running Javascript, etc.

          Between the initial request and a "post-back", code running on the server typically has no connection to the client.


          "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

          "These people looked deep within my soul and assigned me a number based on the order in which I joined" - Homer

          T 1 Reply Last reply
          0
          • Richard DeemingR Richard Deeming

            You'd have to use client-side code to initiate a post-back. For example:

            <asp:FileUpload runat="server" onchange="this.form.submit()" />

            protected void Page_Load(object sender, EventArgs e)
            {
            if (IsPostBack)
            {
            ProcessFileUpload();
            }
            }

            Background threads almost never make sense in ASP.NET, due to the way it works:

            1. The browser makes a request to the server;
            2. The server maps the request to a handler - in this case, you page;
            3. The server creates an instance of your page to handle the request;
            4. The page builds its control tree;
            5. If the request is a "post-back", the page rehydrates the control tree from the saved state sent in the request;
            6. The page runs through the event handlers, and renders an HTML document;
            7. The document is sent back to the client, and the page instance is destroyed;
            8. The client parses and displays the HTML document - this can involve making further requests, running Javascript, etc.

            Between the initial request and a "post-back", code running on the server typically has no connection to the client.


            "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

            T Offline
            T Offline
            turbosupramk3
            wrote on last edited by
            #5

            Maybe I am going about it the wrong way. When I use fileupload and have a path for a file inside of the textbox associated with the fileupload control, I want to preview the picture. Am I going about this the right way?

            Richard DeemingR 1 Reply Last reply
            0
            • T turbosupramk3

              Maybe I am going about it the wrong way. When I use fileupload and have a path for a file inside of the textbox associated with the fileupload control, I want to preview the picture. Am I going about this the right way?

              Richard DeemingR Offline
              Richard DeemingR Offline
              Richard Deeming
              wrote on last edited by
              #6

              You might struggle to get that working with older browsers, but most modern browsers[^] can do that on the client-side. (The notable exception being IE10 or earlier.) There are various pre-built plugins to do this - for example:

              • Upload Preview jQuery Plugin[^] (uses jQuery[^]);
              • Bootstrap File Input - © Kartik[^] (uses Bootstrap[^])

              Or you could roll-your-own - this StackOverflow answer[^] seems like a good place to start.


              "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

              "These people looked deep within my soul and assigned me a number based on the order in which I joined" - Homer

              T 1 Reply Last reply
              0
              • Richard DeemingR Richard Deeming

                You might struggle to get that working with older browsers, but most modern browsers[^] can do that on the client-side. (The notable exception being IE10 or earlier.) There are various pre-built plugins to do this - for example:

                • Upload Preview jQuery Plugin[^] (uses jQuery[^]);
                • Bootstrap File Input - © Kartik[^] (uses Bootstrap[^])

                Or you could roll-your-own - this StackOverflow answer[^] seems like a good place to start.


                "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

                T Offline
                T Offline
                turbosupramk3
                wrote on last edited by
                #7

                The stackflow answer is great and I can see it working exactly as I would like here Edit fiddle - JSFiddle[^] but I cannot get it to work in Visual Studio with my own project? Below is what I have, I feel like this is a pretty dumb question, but I cannot figure out what is wrong?

                <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Updater.aspx.cs" Inherits="Updater.Updater" %>

                <script language=javascript>
                function readURL(input) {

                    if (input.files && input.files\[0\]) {
                        var reader = new FileReader();
                
                        reader.onload = function (e) {
                            $('#blah').attr('src', e.target.result);
                        }
                
                        reader.readAsDataURL(input.files\[0\]);
                    }
                }
                
                $("#imgInp").change(function () {
                    readURL(this);
                });
                

                </script>

                <!DOCTYPE html>

                <html xmlns="http://www.w3.org/1999/xhtml">
                <head runat="server">
                <title>Exchange Avatar</title>

                </head>
                <body>
                <form id="form1" runat="server">
                <br /><br /><br />

                     <input type='file' id="imgInp" />
                <img id="blah" src="#" alt="your image" />
                 </form>
                

                </body>
                </html>

                Richard DeemingR 1 Reply Last reply
                0
                • T turbosupramk3

                  The stackflow answer is great and I can see it working exactly as I would like here Edit fiddle - JSFiddle[^] but I cannot get it to work in Visual Studio with my own project? Below is what I have, I feel like this is a pretty dumb question, but I cannot figure out what is wrong?

                  <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Updater.aspx.cs" Inherits="Updater.Updater" %>

                  <script language=javascript>
                  function readURL(input) {

                      if (input.files && input.files\[0\]) {
                          var reader = new FileReader();
                  
                          reader.onload = function (e) {
                              $('#blah').attr('src', e.target.result);
                          }
                  
                          reader.readAsDataURL(input.files\[0\]);
                      }
                  }
                  
                  $("#imgInp").change(function () {
                      readURL(this);
                  });
                  

                  </script>

                  <!DOCTYPE html>

                  <html xmlns="http://www.w3.org/1999/xhtml">
                  <head runat="server">
                  <title>Exchange Avatar</title>

                  </head>
                  <body>
                  <form id="form1" runat="server">
                  <br /><br /><br />

                       <input type='file' id="imgInp" />
                  <img id="blah" src="#" alt="your image" />
                   </form>
                  

                  </body>
                  </html>

                  Richard DeemingR Offline
                  Richard DeemingR Offline
                  Richard Deeming
                  wrote on last edited by
                  #8

                  The <script> block needs to be within the document - just before the closing </body> tag would be a good place. You also need to add a reference to jQuery, since you're using it to wire up the event handler. The jQuery CDN[^] is probably the simplest way to add this. There's no need for the xmlns declaration on the <html> tag, since you're using HTML5, not XHTML. You also don't need the language attribute on the <script> tag, since Javascript is the only supported language.

                  <!DOCTYPE html>
                  <html>
                  <head runat="server">
                  <title>Exchange Avatar</title>
                  </head>
                  <body>
                  <form id="form1" runat="server">
                  <br /><br /><br />
                  <input type="file" id="imgInp" />
                  <img id="blah" src="#" alt="your image" />
                  </form>

                  <!-- Include jQuery: -->
                  <script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" crossorigin="anonymous"></script>
                  
                  <!-- Your script: -->
                  <script>
                  function readURL(input) {
                      if (input.files && input.files\[0\]) {
                          var reader = new FileReader();
                          reader.onload = function (e) {
                              $("#blah").attr("src", e.target.result);
                          }
                          reader.readAsDataURL(input.files\[0\]);
                      }
                  }
                  
                  $("#imgInp").change(function () {
                      readURL(this);
                  });
                  </script>
                  

                  </body>
                  </html>


                  "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

                  "These people looked deep within my soul and assigned me a number based on the order in which I joined" - Homer

                  T 1 Reply Last reply
                  0
                  • Richard DeemingR Richard Deeming

                    The <script> block needs to be within the document - just before the closing </body> tag would be a good place. You also need to add a reference to jQuery, since you're using it to wire up the event handler. The jQuery CDN[^] is probably the simplest way to add this. There's no need for the xmlns declaration on the <html> tag, since you're using HTML5, not XHTML. You also don't need the language attribute on the <script> tag, since Javascript is the only supported language.

                    <!DOCTYPE html>
                    <html>
                    <head runat="server">
                    <title>Exchange Avatar</title>
                    </head>
                    <body>
                    <form id="form1" runat="server">
                    <br /><br /><br />
                    <input type="file" id="imgInp" />
                    <img id="blah" src="#" alt="your image" />
                    </form>

                    <!-- Include jQuery: -->
                    <script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" crossorigin="anonymous"></script>
                    
                    <!-- Your script: -->
                    <script>
                    function readURL(input) {
                        if (input.files && input.files\[0\]) {
                            var reader = new FileReader();
                            reader.onload = function (e) {
                                $("#blah").attr("src", e.target.result);
                            }
                            reader.readAsDataURL(input.files\[0\]);
                        }
                    }
                    
                    $("#imgInp").change(function () {
                        readURL(this);
                    });
                    </script>
                    

                    </body>
                    </html>


                    "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

                    T Offline
                    T Offline
                    turbosupramk3
                    wrote on last edited by
                    #9

                    Thanks for the reply and the code, does this preview the image on your machine? For some reason it does not on my machine and when I change the form to add an onchange event it tells me that "imagepreview is undefined" ?

                    <form id="form1" runat="server">
                    <br /><br /><br />
                    <input type="file" id="imgInp" onchange="imagepreview(imgInp);" />
                    <img id="blah" src="#" alt="your image" />
                    </form>

                    I even have this function as well, inside of the script tags

                    function imagepreview(input) {
                    if (input.file && input.files[0] {

                                var fildr = new FileReader();
                                fildr.onload = function(e) {
                                    $('#imgprw').attr('src', e.target.result);
                                }
                                fildr.readAsDataURL(input.files\[0\]);
                    
                    Richard DeemingR 1 Reply Last reply
                    0
                    • T turbosupramk3

                      Thanks for the reply and the code, does this preview the image on your machine? For some reason it does not on my machine and when I change the form to add an onchange event it tells me that "imagepreview is undefined" ?

                      <form id="form1" runat="server">
                      <br /><br /><br />
                      <input type="file" id="imgInp" onchange="imagepreview(imgInp);" />
                      <img id="blah" src="#" alt="your image" />
                      </form>

                      I even have this function as well, inside of the script tags

                      function imagepreview(input) {
                      if (input.file && input.files[0] {

                                  var fildr = new FileReader();
                                  fildr.onload = function(e) {
                                      $('#imgprw').attr('src', e.target.result);
                                  }
                                  fildr.readAsDataURL(input.files\[0\]);
                      
                      Richard DeemingR Offline
                      Richard DeemingR Offline
                      Richard Deeming
                      wrote on last edited by
                      #10

                      The code I posted works fine on my machine. Which browser are you using?

                      turbosupramk3 wrote:

                      if (input.file && input.files[0] {

                      You're missing a closing ) on that line.


                      "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

                      "These people looked deep within my soul and assigned me a number based on the order in which I joined" - Homer

                      T 1 Reply Last reply
                      0
                      • Richard DeemingR Richard Deeming

                        The code I posted works fine on my machine. Which browser are you using?

                        turbosupramk3 wrote:

                        if (input.file && input.files[0] {

                        You're missing a closing ) on that line.


                        "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

                        T Offline
                        T Offline
                        turbosupramk3
                        wrote on last edited by
                        #11

                        I thought I had IE11, but it is actually IE9 which I'm going to guess is my problem? I also tried Chrome (v 52.xx) and Firefox (v 28) and neither of those worked either?

                        Richard DeemingR 1 Reply Last reply
                        0
                        • T turbosupramk3

                          I thought I had IE11, but it is actually IE9 which I'm going to guess is my problem? I also tried Chrome (v 52.xx) and Firefox (v 28) and neither of those worked either?

                          Richard DeemingR Offline
                          Richard DeemingR Offline
                          Richard Deeming
                          wrote on last edited by
                          #12

                          IE10 and earlier doesn't support the APIs needed to preview images. Firefox and Chrome should be fine, though. Check the developer console to see if you're getting any errors.


                          "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

                          "These people looked deep within my soul and assigned me a number based on the order in which I joined" - Homer

                          T 1 Reply Last reply
                          0
                          • Richard DeemingR Richard Deeming

                            IE10 and earlier doesn't support the APIs needed to preview images. Firefox and Chrome should be fine, though. Check the developer console to see if you're getting any errors.


                            "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

                            T Offline
                            T Offline
                            turbosupramk3
                            wrote on last edited by
                            #13

                            I'm only getting 2 warning messages Warning 2 Validation (HTML5): Attribute 'crossorigin' is not a valid attribute of element 'script'. c:\users\xxxxx\documents\visual studio 2012\Projects\Updater\Updater\Updater.aspx 122 128 Warning 1 Validation (HTML5): Attribute 'integrity' is not a valid attribute of element 'script'. c:\users\xxxxx\documents\visual studio 2012\Projects\Updater\Updater\Updater.aspx 122 64

                            Richard DeemingR 1 Reply Last reply
                            0
                            • T turbosupramk3

                              I'm only getting 2 warning messages Warning 2 Validation (HTML5): Attribute 'crossorigin' is not a valid attribute of element 'script'. c:\users\xxxxx\documents\visual studio 2012\Projects\Updater\Updater\Updater.aspx 122 128 Warning 1 Validation (HTML5): Attribute 'integrity' is not a valid attribute of element 'script'. c:\users\xxxxx\documents\visual studio 2012\Projects\Updater\Updater\Updater.aspx 122 64

                              Richard DeemingR Offline
                              Richard DeemingR Offline
                              Richard Deeming
                              wrote on last edited by
                              #14

                              Try using the developer tools to step through the function. Debug with Breakpoints | Web Tools - Google Developers[^] Debugger - Firefox Developer Tools | MDN[^]


                              "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

                              "These people looked deep within my soul and assigned me a number based on the order in which I joined" - Homer

                              T 1 Reply Last reply
                              0
                              • Richard DeemingR Richard Deeming

                                Try using the developer tools to step through the function. Debug with Breakpoints | Web Tools - Google Developers[^] Debugger - Firefox Developer Tools | MDN[^]


                                "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

                                T Offline
                                T Offline
                                turbosupramk3
                                wrote on last edited by
                                #15

                                I think it is something where the entire image path has to be in the code. Thank you for the help

                                1 Reply Last reply
                                0
                                Reply
                                • Reply as topic
                                Log in to reply
                                • Oldest to Newest
                                • Newest to Oldest
                                • Most Votes


                                • Login

                                • Don't have an account? Register

                                • Login or register to search.
                                • First post
                                  Last post
                                0
                                • Categories
                                • Recent
                                • Tags
                                • Popular
                                • World
                                • Users
                                • Groups