how to upload file via c# code

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • thevinh92
    New Member
    • Aug 2012
    • 10

    #16
    Thanks, Frinavale! That's exactly what i'm going to do! But, can you tell me how to do in the aspx page!

    Comment

    • Frinavale
      Recognized Expert Expert
      • Oct 2006
      • 9749

      #17
      The aspx page responsible for managing uploading of files will probably have all of it's code in the Page Load event. It would be similar to what ariful alam suggested in post #8..except that you don't need to use the FileUpload control because you'll be retrieving the file from the Request object and the code would be in the PageLoad event instead of a button click event.


      For example,

      If you created an asp.net web application and added an new WebForm to it called "SaveImage" you would have the following in the ASP.NET code:

      Code:
      <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.SaveImage" %>
      
      <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
      
      <html xmlns="http://www.w3.org/1999/xhtml">
      <head runat="server">
          <title></title>
      </head>
      <body>
          <form id="form1" runat="server"  enctype="multipart/form-data">
          <div>
      
          <input type="file" id="imageToUpload" name="imageToUpload"  runat="server"/>
          <asp:Button runat="server" ID="btnUploadFile" Text="Upload" />
      
          </div>
          </form>
      </body>
      </html>

      Your C# code would simply be:
      Code:
      using System;
      using System.Collections.Generic;
      using System.Linq;
      using System.Web;
      using System.Web.UI;
      using System.Web.UI.WebControls;
      
      namespace WebApplication1
      {
          public partial class SaveImage : System.Web.UI.Page
          {
              protected void Page_Load(object sender, EventArgs e)
              {
                  HttpPostedFile file = Request.Files["imageToUpload"];
      
                  //check file was submitted
                  if (file != null && file.ContentLength > 0)
                  {
                      string fname = file.FileName;
                      file.SaveAs(Server.MapPath(string.Format("~/Images/{0}", fname)));
                  }
      
              }
          }
      }

      The above code uses an Images folder to store the images into. You should either add an Images folder to your ASP.NET application so you have somewhere to store the images... or use file.SaveAs(Ser ver.MapPath(str ing.Format("~/{0}", fname))); instead.

      If you compile and run this application you will be able to pick a file, hit the button, and it will upload and save it to the folder specified (either the Images folder or the root of the running project).

      You don't even really need the button...but it's there so that you can just test the ASP.NET save logic.

      There is no validation in my logic either...you SHOULD put validation logic into your code to ensure that you are only uploading files that you are expecting.

      Once you have this working, you will have to write the Desktop application that uses the HttpWebRequest class to request the page you just implemented and to write the image back up to the server.

      Make sure that your header content-type matches what the server is expecting.

      -Frinny

      Comment

      • thevinh92
        New Member
        • Aug 2012
        • 10

        #18
        Thanks Frinavale! I test your code, it's very good!
        And, here is my code in the client, and i don't know where it wrong:
        Code:
        string Url = "http://localhost:2595/SaveImage.aspx";
                    Uri passUrl = new Uri(Url);
                    HttpWebRequest httpWR = (HttpWebRequest)HttpWebRequest.Create(Url);
                    httpWR.Method = "POST";
                    httpWR.ContentType = "multipart/form-data; boundary=" +  boundary;
                    httpWR.KeepAlive = true;
                    httpWR.Credentials = System.Net.CredentialCache.DefaultCredentials; 
                    byte[] bytes = File.ReadAllBytes(@txtPath.Text);
                    httpWR.ContentLength = bytes.Length;
                    Stream rs = httpWR.GetRequestStream();
                    rs.Write(bytes, 0, bytes.Length);
                    rs.Close();
        Please help me!

        Comment

        • Frinavale
          Recognized Expert Expert
          • Oct 2006
          • 9749

          #19
          thevinh92, I've never used the HttpWebRequest class before to do such a thing.

          You have to give me a clue as to What is wrong?
          Are you getting an error?
          Is it doing something incorrectly?
          Give me more details about the problem....

          -Frinny

          Comment

          • Frinavale
            Recognized Expert Expert
            • Oct 2006
            • 9749

            #20
            Now that you have your ASP.NET page working as per post #17...

            I tried your code and it never even hit the ASP.NET code because you don't call the HttpWebRequest' s GetResponse method.

            Also, you need to specify what your boundary is, and write the boundary delimiter around your content.

            And you need to specify the "Key" for the file so that the ASP.NET code can retrieve the file....and you need to specify the file name that you want the file to have on the server...

            I wrote a quick WPF application that has a single button that allows the user to browse to a .jpg image to select for uploading. It then uploads the picture using the HttpWebRequest class.

            Please note that if your image is too big, it will crash in the ASP.NET server code.

            Again, I have no validation code or checks or anything....

            Code:
             private void uploadImage_Click(object sender, RoutedEventArgs e)
                    {
                        // Configure open file dialog box
                        Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
                        dlg.FileName = "Image"; // Default file name
                        dlg.DefaultExt = ".jpg"; // Default file extension
                        dlg.Filter = "Images (.jpg)|*.jpg"; // Filter files by extension
            
                        // Show open file dialog box
                        Nullable<bool> result = dlg.ShowDialog();
            
                        // Process open file dialog box results
                        if (result == true)
                        {
                            string filePath = dlg.FileName; // Get the image path
                            string url = "http://localhost:50802/SaveImage.aspx";
                            string boundary = string.Format("----------------------------{0}", DateTime.Now.Ticks.ToString("x"));//The boundary for the file(s) to upload
            
                            HttpWebRequest uploadImageHttpWebRequest = (HttpWebRequest)WebRequest.Create(url);//used to upload the image to theh server
                            uploadImageHttpWebRequest.ContentType = string.Format("multipart/form-data; boundary={0}", boundary);//indicating the boundary and content type
                            uploadImageHttpWebRequest.Method = "POST";//indicating that we are using POST to send the data to the server
                            uploadImageHttpWebRequest.KeepAlive = true;
            
                            Stream memStream = new System.IO.MemoryStream();//used to collect the necessary information to send to the server...starting with the beginning boundary 
                            byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
                            memStream.Write(boundarybytes, 0, boundarybytes.Length);
            
            
                            string[] fileNameTokens = filePath.Split('\\');//retrieving the file's name
                            string fileName = string.Format("{0}{1}",DateTime.Now.Ticks.ToString("x"),fileNameTokens[fileNameTokens.Length - 1]);//genearting a unique file name to save on the server
            
                            //indicating the Key for the file that we are uploading ('name') and the name of the file as we want it to appear on the server ('filename')
                            string header = string.Format("Content-Disposition: form-data; name=\"imageToUpload\"; filename=\"{0}\"\r\n Content-Type: application/octet-stream\r\n\r\n", fileName);
                            byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
                            memStream.Write(headerbytes, 0, headerbytes.Length);
            
                            //Reading the file and writing it to the memStream
                            using (FileStream fileStream = File.Open(filePath, FileMode.Open, FileAccess.Read))
                            {
                                byte[] buffer = new byte[1024];
                                int bytesRead = 0;
                                while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                                {
                                    memStream.Write(buffer, 0, bytesRead);
                                }
            
                            }
            
                            //writing the closing boundary 
                            memStream.Write(boundarybytes, 0, boundarybytes.Length);
                            uploadImageHttpWebRequest.ContentLength = memStream.Length; //indicating the length of the content
                            Stream requestStream = uploadImageHttpWebRequest.GetRequestStream();//retrieving the stream that will be used to upload the file to the server
            
                            //writing the memory stream into a byte array and writing that byte array to the stream used to upload the file to the server
                            memStream.Position = 0;
                            byte[] tempBuffer = new byte[memStream.Length];
                            memStream.Read(tempBuffer, 0, tempBuffer.Length);
                            memStream.Close();//cleaning up our memory stream since we aren't using it any more
            
                            requestStream.Write(tempBuffer, 0, tempBuffer.Length);
                            requestStream.Close();
            
                            WebResponse uploadResponse = uploadImageHttpWebRequest.GetResponse();//this sends the request to the server and uploads the file
                            uploadResponse.Close();//clean up the response
                            uploadImageHttpWebRequest = null;//clean up the request
                            uploadResponse = null;
            
                        }
                    }
            My code only uploads a single image to the server.
            I had it working in such a way that it could upload more than one image though...it requires simple changes to the above code and requires changes to the server side code as well but the exercise was fun because before now I had never used the HttpWebRequest class.

            -Frinny
            Last edited by Frinavale; Nov 2 '12, 01:22 PM.

            Comment

            • thevinh92
              New Member
              • Aug 2012
              • 10

              #21
              Oh, Frinavale, Thank you very much! You don't know how i be happy when i test your code and it run successfully!
              And, i still need to ask you more question:
              How can i download the Image that i upload If i use HttpWebRequest with the method = "GET"?
              Thanks again!

              Comment

              • Frinavale
                Recognized Expert Expert
                • Oct 2006
                • 9749

                #22
                @thevinh92, the only time I have ever used the HttpWebRequest is to help you with this question. I don't know how to do what you are asking off right now and it may take me a few days before I am able to sit down and play with it more.

                I suggest researching the topic in the mean time to try and get something to work. That way we can work with code that you have written and tried when I am able to check it out.

                On top of that, you should start a new thread for your new question :)

                On this forum, you should stick to one question per thread to keep things simple.

                Your question is wondering away from ASP.NET and falling under the domain of the C# forum.

                -Frinny

                Comment

                Working...